Tải bản đầy đủ - 0 (trang)
Hack 30. Use Ajax with a Google Maps and Yahoo! Maps Mash-up

Hack 30. Use Ajax with a Google Maps and Yahoo! Maps Mash-up

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

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



TheHTMLpagedividestheapplicationintotworegionsusing

divtagsandCSSstyles.TheGoogleMapsitsontheleftside.

Figure4-3showsthemash-upaftertheuserclicksonthe

GoogleMaptospecifyacoordinate,thenclickstheYahoo!Map

button.TheYahoo!Mapisshownontherightsideofthe

screen.



Figure4-3.GoogleandYahoo!,dukingitout



Figure4-4showstheapplicationwhentheuserhaschangedto

satellitemodeintheGoogleMapandzoomedoutabitinthe

Yahoo!Map.



Figure4-4.Changingtosatellitemode



Iftheuserrequestsdrivingdirections,theyappearintheright

partofthescreen,asinFigure4-5.



Figure4-5.MarryingGoogleMapsandYahoo!

directions



GoogleMapsprovideslatitude/longitudecoordinatesforanywhereon

earth,butYahoo!'sdrivingdirectionscannotpresentlyprovide

directionsbetweenplacesthatareseparatedbybodiesofwatersuch

asoceansorbays.IfyouclickonanislandinaGoogleMap,for

example,youwillgetthelatitude/longitudepoint.However,the

directionswillbeblankbecauseYahoo!drivingdirections,asofthis

writing,donotconnectmainlandoriginswithislanddestinations.



FallHarvest

Agoodchunkoftheworkforthedriving-directionsmechanism

isdonebytheservercomponent,whichharveststhedirections

fromaYahoo!page.Specifically,theGooglerequestobject

sendsalongaYahoo!-relatedURLthatincludestheuser's

chosenlatitudeandlongitudecoordinates.Theserver

componentthen:



1. MakesarequesttoYahoo!usingtheURL

2. ReceivesallthecodefortheYahoo!page

3. Scrapesthedrivingdirectionsfromthepage

4. Sendsjustthischunkofdatabacktotheapplication,which

displaysthedirectionsintherightframe

Thischunkofdataintheresponseisadivelementcontaininga

numberedlistofdrivingdirections,asin:

1. TakearightonMainStreetandgo1.2miles.

2. Goonthehighwayforanother680miles....



HTML

Let'slookatsomeoftheHTMLcodeforthepagethat'sloaded

intothemash-upuser'sbrowser.I'lljustshowthetoppartof

theHTMLcodethatsetsthisapplicationinmotion:




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







.cont{float:left;height:500px;

width:500px;}

.instructions{font-size:0.8em;}

.label{font-size:0.9em;}




"http://maps.google.com/maps?file=api&v=1&key=ABQIAAAANJd_P

f0RhwHhZhSkdb7FxCoFqdzTrRB9tjTtDcnrVRSo66iNyUFvtz5XXXXXXXXX

type="text/javascript">




"text/javascript">


"text/javascript">


"http://api.maps.yahoo.com/ajaxymap?v=2.0&appid=YRXXXXXXXXX

MapMash-Up





UseGoogleMapsandYahoo!Maps







...



ThefirstscripttagimportstheGoogleMapsobjectsthatwecan

useasofficialGooglehackers.TheseareJavaScriptobjects

suchasGMapthatallowthecodetoaddandcontrolmapsona

webpage.Thesrcattributeofthescripttagincludesthelong,

involvedURLforimportingGoogle'sspecialcode,aswellasthe

developer-specifickey[Hack#28].(TheXXXshavebeenadded

becauseweshouldn'tpublishtheexactkeysweareusing.)

TheJavaScriptcodeappearsinthefilehacks4_1_b.js.script

tagsimportthatcode,whichyou'llseeinanupcomingsection,

aswellasthecodethatusesXMLHttpRequest[Hack#3].

Finally,theHTMLcodeimportstheYahoo!Mapsrelatedcode

withanotherscripttag.Thiscodebaseisnecessaryforweb

pagesthatembedYahoo!Maps.TheURLforthispurpose

includesanappidparameterspecifyingyourownapplicationID

forYahoo!Maps:


"http://api.maps.yahoo.com/ajaxymap?v=2.0&appid=YRXXXXXXXXXXX



GoogleandYahoo!,ToetoToe

HereistheJavaScriptcodeinthehacks4_1_b.jsfile.The

createMap()functiondoesnotneedfurtherexplanationbecause

wediscusseditinthelasthack.Let'sfocusonthecodethat

embedsaYahoo!Mapandprovidesdrivingdirections:



varmap=null;

window.onload=function(){

createMap();

document.getElementById("submit").onclick=function(){

getDirections(document.forms[0]._street.value,

document.forms[0]._city.value,

document.forms[0]._state.value,

document.forms[0]._dname.value,

document.forms[0]._latitude.value,

document.forms[0]._longitude.value);

};

document.getElementById("rem_bubbles").onclick=function()

clearOverlays();

};



document.getElementById("yah_maps").onclick=function(){

createYMap();

};

};

functioncreateYMap(){

writeMap(document.forms[0]._latitude.value,

document.forms[0]._longitude.value);

}

functioncreateMap(){

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());

//centeronroughlymiddleofUSA

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

}

functionclearOverlays(){

if(map!=null){

map.clearOverlays();

}

}

functiongetDirections(street,city,state,

destName,lat,lng){

var_str=encodeURIComponent(street);

var_cit=encodeURIComponent(city);

varurl="http://www.parkerriver.com/s/dd?"+_str+"&tlt="+

lat+"&tln="+lng+"&csz="+

_cit+"%2C"+state+"&country=us&tname="+destName;

httpRequest("GET",url,true,handleResponse);

}



//eventhandlerforXMLHttpRequest

functionhandleResponse(){

try{

if(request.readyState==4){

if(request.status==200){

var_dirs=request.responseText;

vartargDiv=document.getElementById("ymap_con

targDiv.innerHTML=_dirs+

'


"window.print()\\">PrintDirections<

}else{

//request.statusisnot200;ommittedforbrevi

}



}//endouterif

}catch(err){

//ommittedforbrevity

}

}



functionwriteMap(lat,lng){

var_point=newYGeoPoint(parseInt(lat),parseInt(lng));

var_map=newYMap(document.getElementById('ymap_container

_map.drawZoomAndCenter(_point,8);

_map.addPanControl();

_map.addZoomLong();

document.getElementById('yah_maps').disabled=true;

}



Agoodplacetostartexplainingthisprogramiswiththe

writeMap()function.Thiscodeshowshoweasyitistoembeda

Yahoo!Map.Thecodepassesthelatitudeandlongitude

coordinatesintotheconstructorforaYGeoPointobject(anobject

providedbyYahoo!Maps).ThecodethencreatesaYMapobject,

specifyingthedivelementthatwillcontaintheYahoo!Map.The

nextthreemethodcallscenterthemaponthespecified

coordinatesatacertainzoomlevel(here,8inarangeof1to

16),thenaddacoupleofYahoo!controlstothemap.

ThelastbitofcodedisablestheYahoo!Mapbutton,because

oneembeddedmapisenough;afterloadingthemap,theuser

canmanipulateittoshowanyotherlocation.



DrivingDirections

Thecodealsocontainsafunctionfordisplayingdriving

directions:



functiongetDirections(street,city,state,

destName,lat,lng){

var_str=encodeURIComponent(street);

var_cit=encodeURIComponent(city);

varurl="http://www.parkerriver.com/s/dd?"+_str+"&tlt="+

lat+"&tln="+lng+"&csz="+

_cit+"%2C"+state+"&country=us&tname="+destName;

httpRequest("GET",url,true);

}



ThisfunctionislaunchedwhentheuserclickstheYahoo!

Directionsbutton.(SeeFigure4-5foraviewofwhatthisscreen

andbuttonlooklike.)Thefunctiontakesthestreet,city,and

statewheretheuserwantstostartthetrip,aswellasthe

latitude,longitude,and(optionally)thepreferrednameforthe

destination,thensendsthisinformationtotheserver

componentthatactuallytalkstotheYahoo!application.

ThefunctionusestheglobalJavaScriptencodeURIComponent()

functiontomakesurethatthestreetandcity,whichmay

encompassmorethanoneword(asin"NewOrleans"),are

properlyencodedforanInternetaddress.Inencodingphrases

forURLs,NewOrleansbecomesNew%20Orleans,forexample.



HowDoIGettoLatitude...?

Iwon'tgointogreatdetailabouthowtheservercomponentis

programmed,excepttosaythattheaddressofthecomponent

isaJavaservletathttp://www.parkerriver.com/s/dd/.The

servletsendsanHTTPrequesttotheYahoo!component,then

siftsthroughthereturnvalueforthechunkofHTML

representingdrivingdirections.Theservletthensendsthese

directionsbacktoourAjaxapplication.



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

Hack 30. Use Ajax with a Google Maps and Yahoo! Maps Mash-up

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

×