Tải bản đầy đủ - 0 (trang)
Hack 29. Use the Google Maps API Request Object

Hack 29. Use the Google Maps API Request Object

Tải bản đầy đủ - 0trang

levelof1displaysatown'sstreets.

Asmentionedpreviously,whentheuserrequeststhisweb

page,theapplicationcaneitherobtaintheuser'susername

fromapreviouslygeneratedcookie,orasktheusertosignin

andfetchthepreferencesfromadatabase.However,weare

notgoingtoshowthatstep(eventhoughitisimportantina

real-worldapplication)becausewesurmisethatthereaderis

moreinterestedintheAPI'sAjax-relatedobjectsandthemapdisplaycode.

HereistheHTMLforthehack:




"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


"urn:schemas-microsoft-com:vml">




PEMs2vnU_f0RhwHhZhQ6pfwiB1eVXKVVHswEcdvw4p5NixS195EO7O7VmH483DM

type="text/javascript">



ViewMap





YourGoogleMap





Yourspecifications







Latitude:





Longitude:





Zoomlevel:













ThiscodeimportstheGoogleAPIlibrarywiththefirstscripttag.

ThistagallowstheapplicationtouseGoogleMapsAPIobjects

suchasGMapandGXmlHttp(whichrepresentstherequestobject).

Thescriptsrcattributeincludesthedeveloperkey,asdescribed

in"GetAccesstotheGoogleMapsAPI"[Hack#28].Another

scripttagimportsintothepageahacks4_1a.jsJavaScriptcode

file,whichcontainsthecustomcodeforourapplication.



GoogleMapsrequiresaseparatedeveloperkeyforeveryURLdirectory

containingGoogleMapsrelatedwebpages.Forexample,Ihavea

developerkeythatcoverseverywebpageinthe

http://www.parkerriver.com/ajaxhacks/directory.Itisextremelyeasy

togenerateadeveloperkeyat

http://www.google.com/apis/maps/signup.html.



Themapitselfisdisplayedwithinadivtagthathasanidofmap.

Whenthebrowserloadsthepage,thecodefirstchecksthe

compatibilityofthebrowserusingaGoogleglobalfunction,

GBrowserIsCompatible().IfthisfunctionreturnsTRue,the

applicationcallsafunctionnamedgoogleAjax().Thewindow.onload

eventhandlerandgoogleAjax()appearinsidethehacks4_1a.js

file.googleAjax()queriesaserverfortheuser'sspecific

preferencesofauserbypassingalongtheusername

("bwperry,"inthiscase).Theapplicationthenusesthe

propertiesfetchedbygoogleAjax()todisplayandzoominona

map.Hereisthecodefromhacks4_1a.js:

varmap=null;

window.onload=function(){



if(GBrowserIsCompatible()){

googleAjax('http://www.parkerriver.com/s/gmap?user=bwpe

}else{alert('YourbrowserisnotcompatiblewithGoogle

};

functioncreateMap(lat,lng,zoomLevel){

map=newGMap(document.getElementById("map"));

GEvent.addListener(map,'click',function(overlay,point){

document.forms[0]._longitude.value=point.x;

document.forms[0]._latitude.value=point.y;

map.addOverlay(newGMarker(point));



});

map.addControl(newGLargeMapControl());

map.addControl(newGMapTypeControl());

if(lat!=null&&lat.length!=0&&lng!=null&&lng.

length!=0&&zoomLevel!=null&&zoomLevel.lengt

map.centerAndZoom(newGPoint(lng,lat),zoomLevel);

}else{

//centeronroughlymiddleofUSA

map.centerAndZoom(newGPoint(-97.20703,40.580584),14)

}

}

functiongoogleAjax(url){



varrequest=GXmlHttp.create();

request.open("GET",url,true);

request.onreadystatechange=function(){

if(request.readyState==4){

if(request.status==200){

varresp=request.responseXML;

varrootNode=resp.documentElement;

varzoom=rootNode.getElementsByTagName("zoomL

varlatLng=rootNode.

getElementsByTagName("centerCoords")[0];

varcoordArr=latLng.firstChild.nodeValue.spli

varzoomLevel=zoom.firstChild.nodeValue;



createMap(coordArr[0],coordArr[1],zoomLevel);

alert(coordArr[0]+""+coordArr[1]+""+zoomLevel

document.forms[0]._latitude.value=coordArr[0];

document.forms[0]._longitude.value=coordArr[1];

document.forms[0]._zoomLevel.value=zoomLevel;

}else{

alert(

"Theapplicationhadaproblemcommunic

"theserver.Pleasetryagain.");

}//innerif

}//outerif

}//endfunction

request.send(null);

}



Itwillprobablyhelpyouvisualizetheapplication'spurposeifI

showyouthemapinsideabrowserwindow,beforedigginginto

thecode.Thepageloadsthemapanddisplaystheuser's

preferredcoordinatesandzoomlevelintextfieldsbeneathit.

Figure4-1showsthepagedisplayedinabrowser.



Figure4-1.GoogleMapcenteredonMAwith

zoomlevel10



MapObjects

TakeaganderatthegoogleAjax()functionanditscreationofan

objectthatmakesHTTPrequests:

functiongoogleAjax(url){



varrequest=GXmlHttp.create();

request.open("GET",url,true);

request.onreadystatechange=function(){

if(request.readyState==4){

if(request.status==200){

varresp=request.responseXML;

varrootNode=resp.documentElement;

varzoom=rootNode.getElementsByTagName("zoomL

varlatLng=rootNode.

getElementsByTagName("centerCoords")[0];

varcoordArr=latLng.firstChild.nodeValue.spli

varzoomLevel=zoom.firstChild.nodeValue;

createMap(coordArr[0],coordArr[1],zoomLevel);

document.forms[0]._latitude.value=coordArr[0];

document.forms[0]._longitude.value=coordArr[1];

document.forms[0]._zoomLevel.value=zoomLevel;

}else{

alert(

"Theapplicationhadaproblemcommunic

"theserver.Pleasetryagain.");

}//innerif

}//outerif

}//endfunction

request.send(null);

}



Rememberallthecodethatcreatedarequestobjectin"Detect

BrowserCompatibilitywiththeRequestObject"[Hack#1]and

"UseYourOwnLibraryforXMLHttpRequest"[Hack#3]?All

that'snecessarywiththeGoogleMapsAPIisvarrequest=

GXmlHttp.create().Youthencalltheopen()andsend()methods

andpointtoafunctionthatwillbeyouronreadystatechangeevent

handler,justasyouwouldwitharequestobjectthatyou

createdwithyourowncode.



TheonreadystatechangeeventhandlerspecifiesaJavaScriptfunctionthat

thecodeusestohandleanHTTPresponse.InAjax,therequestobject

queriesaserver,whichtypicallysendsbackaresponse.Youcanhave

theeventhandlerrefertoafunctionliteral(asinthiscode)ortothe

nameofafunction(withoutthe()characters)thatyouhavedefined

elsewhereinthecode(see"DetectBrowserCompatibilitywiththe

RequestObject"[Hack#1]).



ThiscodefetchesanXMLdocumentfromtheserverthat

containstheuser'smappreferences:

varresp=request.responseXML;



ThereturnedXMLdatamightlooklikethis:



42.057450220246-71.64184570312

10





RememberthatyouaregettingthisXMLinformationfromthe

server.Thedataisspecifictoeachuserandcanbestoredina

database.Thisinformationrepresentstheuser'spreferred

latitudeandlongitudeforthecenterpointofthemap,aswell

asthepreferredzoomlevel.



InGoogleMaps,latitudeismeasuredintherange90degreesnorthof

theequatorto90degreessouthoftheequator.Longitudeismeasured

inarangeof180degreeseastoftheGreenwichMeridianto180

degreeswestoftheGreenwichMeridian.



ThecodethenusesDocumentObjectModelprogrammingto

pullthetextvaluesoutoftheXMLdocumentandusethemfor

mapdisplay:

varrootNode=resp.documentElement;

varzoom=rootNode.getElementsByTagName("zoomLevel")[0];

varlatLng=rootNode.getElementsByTagName("centerCoords")[0];

varcoordArr=latLng.firstChild.nodeValue.split("");

varzoomLevel=zoom.firstChild.nodeValue;

createMap(coordArr[0],coordArr[1],zoomLevel);

document.forms[0]._latitude.value=coordArr[0];

document.forms[0]._longitude.value=coordArr[1];

document.forms[0]._zoomLevel.value=zoomLevel;



Therootnodeisthetop-levelXMLelement,suchasmapSetup.

TheDOMDocumentobjecthasadocumentElementpropertythat

returnsareferencetothiselement.Thecodethenstores

referencestotheelementsthatholdthedataonthe

coordinatesforthecenterpointofthemapandthezoomlevel

invariablesnamedlatlngandzoom,respectively.

HowdoyougetthevaluesofelementsusingDOM?Thelatlng

variable,forinstance,isofaNodetype.TheNodehasaproperty

namedfirstChild,which(phew!)returnsthetextnode

containedbytheXMLelement.Thecodegetsthetextvalueof

thisNodeusingtheNode'snodeValueproperty.

ThecenterCoordselementcontainsbothlatitudeandlongitude

values,separatedbyaspacecharacter.Thus,callingthestring

split()methodreturnsanarraythatcontainsthelatitudeasthe

firstarraymemberandthelongitudeasthesecondmember.



Youcanredesigntheservercomponenttoreturnthelatitudeand



longitudeinseparateXMLelements.



CreatingYourOwnMap

ThecreateMap()functionusesGoogleMapsobjectstogeneratea

mapforthewebpage.Thecodecallsthisfunctionwiththe

user'spreferredlatitude,longitude,andzoomlevelas

parameters,asin:

createMap(coordArr[0],coordArr[1],zoomLevel)



Thefirsttwoparametersarearraymembers,whichiswhythecode

uses,forexample,thecoordArr[0]syntax.



UnlikeinotherAjaxlibraries,whenusingtheGoogleMapsAPI,

thedeveloperdoesnothavetodealwiththebasicsof

XMLHttpRequest.However,ifyourapplicationrequiresmorecontrol

overtherequestobject,youcaninitiateasetupliketheone

describedin[Hack#3],whichimportsitsownJavaScriptfile

thathandlesHTTPrequests.







Hack30.UseAjaxwithaGoogleMapsand

Yahoo!MapsMash-up



UseGoogleMapsinawebapplicationwithYahoo!Maps

anddrivingdirections.

BothGoogleandYahoo!providedeveloperswithpowertoolsfor

manipulatingmapswithintheirownwebapplications."Get

AccesstotheGoogleMapsAPI"[Hack#28]introducedreaders

totheGoogleMapsAPI;Yahoo!inturnprovidestheYahoo!

MapsAPI,whichincludesaspecificAPIforAjaxdevelopers(see

http://developer.yahoo.net/maps/ajax/index.html).

Yahoo!Mapsisveryeasytogetstartedwith;justacquirean

applicationIDfromtheaboveURL,thenbeginembedding

Yahoo!Mapsandcontrolsinsideyourwebpages.Youhaveto

includetheapplicationIDintheURLthatembedsamapinside

yourwebpage,whichyou'lllearnhowtodointheupcoming

hackdescription.

ThishackusesboththeYahoo!MapsandGoogleMapsAPIs.

Combiningtwotechnologiesinawebapplicationissometimes

referredtoasamash-up,anexpressionthatderivespartly

fromthemusicindustry.ThiswaywecanviewaGoogleMapon

theleftsideofthescreen,perhapsinsatelliteview,andthe

samegeographicalregioninaYahoo!Maponthescreen'sright

side.Themash-upalsoallowstheusertoclickonadestination

onaGoogleMapandaccessYahoo'sdrivingdirections.



HowItWorks



ThishackfirstsetsupaGoogleMaponawebpageusingthe

GoogleMapsAPI.Theapplicationaskstheusertoclickonthe

maptospecifyamapcoordinate,andoptionally,typeinan

originaddressfordrivingdirections.Userscanzoominon

differentmapcoordinatesandareaspriortoclickinga

destinationpoint.

Thedestinationisspecifiedintermsoflatitudeandlongitude.A

littleballooniconpopsupontheGoogleMapwhereverthe

mouseisclicked.WhentheuserclickstheYahoo!Mapbutton,a

Yahoo!Mapappearsonthescreen'srightside,centeredonthe

specifiedlatitudeandlongitude.Theusercanthenoptionally

puttheGoogleMapintosatelliteview,whilemanipulatingthe

Yahoo!Mapwithitssophisticatedcontrols.

Toobtaindrivingdirections,theusercanenteranorigin

addressintheleftsidetextfieldsandthenclicktheYahoo!

Directionsbutton.Theapplicationusestheindicated

latitude/longitudecoordinatestoscrapethedrivingdirections

offofaYahoo!HTTPresponse.Thehackthenreplacesthe

Yahoo!Mapwiththestep-by-stepdrivingdirections.

Figure4-2showswhattheapplicationlookslikeinaweb

browserbeforetheuserclickstheYahoo!Mapbutton.



Figure4-2.Chooseyourdestination



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 29. Use the Google Maps API Request Object

Tải bản đầy đủ ngay(0 tr)

×