Tải bản đầy đủ - 0 (trang)
Hack 115. Drop a Google Map Onto Your Site

Hack 115. Drop a Google Map Onto Your Site

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

Satellite,andTerrainview.Insomeareas,morebuttons

areavailable.



NOTE

GoogleMapsisalsoavailableformobilephones.This

includesdirections,and,forsomecitiesintheUnited

States,thedisplayofreal-timetrafficdatatohelpyou

avoidtrafficjams.TodownloadGoogleMapsforyour

phoneorPDA,visithttp://google.com/gmmfromyour

phone'swebbrowser.Ifyourphoneissupported,you'll

beabletoinstallitovertheair.

GoogleEarth

GoogleEarth(http://earth.google.com),picturedinFigure112,isthedesktopsiblingofGoogleMaps.Afterlaunchingit,

you'llseethatitsrotating3Dglobeisabitmorefluidthanthe

flat2DviewofGoogleMaps.GoogleEarthinitsbasicversionis

free,butthepaidversionletsyougeneratevideoswitheffects

suchasseamlesslyzoomingintoalocation—thekindofeffect

you'dseeinTVnewscoverage.

Atthistime,GoogleEarthhasthemostcompletesupportfor

KeyholeMarkupLanguageinformationfiles—includingsupport

foranimations.Manyorganizationshavedataoverlaysthatyou

cansuperimposeontheglobebycheckingtherespectiveboxes

oftheLayerspane.AWikipedialayeraddslocation-relevant



informationfromtheonlineencyclopedia;theWeatherlayers

allowyoutodisplaycloudsandforecasts;NationalGeographic

magazineprovidesalayerwithregionalinformation,including

photos,aswell.

LaunchingGoogleEarth,softwareformerlyknownas

KeyholeEarthViewer



GoogleSketchUp

GoogleSketchUp(http://sketchup.google.com)isa3Dprogram

forarchitectsdraftingtheirwork,orhobbydesignersinterested

increatinga3Dshape.LikeGoogleEarth,SketchUpisnota

webapplication,butinsteadrequiresyoutoinstallan"offline"

client,aspicturedinFigure11-3.TheemphasisofSketchUpis

oneaseofuse;althoughyoumaynotbeabletodoanything

andeverythingwithit,whatyoucandocanoftenbedonevery

quickly,withlittleeffort.Andwhatever3Dmodelyoucreatein

SketchUp,youcanthenincludeinGoogleEarth.

AgreatwaytostartlearningaboutSketchUpistofollowthe

onlinevideotutorialsat

http://sketchup.google.com/tutorials.html.Onceyou'vecreated

somethinguniqueandinteresting,youcanuploadittothe



Google3DWarehousesite,adirectoryofshared3Dmodels.

Youcanalsoimportanymodelyoufindatthe3DWarehouse

intoyourowncreations.

TheSketchUp3Deditor



Hack115.DropaGoogleMapOntoYour

Site

TakeyourGooglemapandrun,freeingitfromitsusualhome

atthemaps.google.comdomain.

TheeasiestwaytoembedaGooglemaponyourownsiteis

availabledirectlyfromhttp://maps.google.com.Justpointto

anylocation—youcanalsozoominandswitchtosatelliteview,

forinstance—andthenclick"Linktothispage"ontop.Adialog

willopenthatallowsyoutocopyanHTMLportiontobepasted

intoyourownsite,asshowninFigure11-4.Youcanalso

customizethemapsizebyclickingthe"Customize"linkinthis

dialog.

Theactualcodeyouendupwithconsistsofaninlineframe,

amongotherthings.Aninlineframeisawindowwithinthe

browserwindowthatcontainsanexternalsite'sservice;inthis

case,GoogleMaps.AnexampleisshowninFigure11-5,and



theaccompanyingHTMLcodeisinFigure11-6.



NOTE

IfyouareconcernedaboutusingHTMLthatvalidates,

youneedtoadjustsomeofGoogle'sHTMLattributes,

andalsosetyourdocumenttypeto"transitional."To

validateyourHTML,enteryourhomepageaddressinto

theofficialvalidatorprovidedbytheWorldWideWeb

Consortiumathttp://validator.w3.org.Thiscanhelp

alertyoutosyntaxerrorsinyourcode.Tolearnmore

aboutHTMLandCSS,visithttp://w3.org/TR/html4/and

http://w3.org/TR/CSS21/respectively.



TheGoogleMapsembeddingdialog



Includingtheembedcodeinasamplehomepage





TheHTMLandCascadingStylesheetfilesbehindthe

samplehomepage



HackingtheHack

Formorecontroloverwhatyourmapdoesandhowitappears,

youcanusetheGoogleMapsAPI(ApplicationProgramming

Interface).InadditiontounderstandingbasicHTML,you'llneed

toknowsomeJavaScript.



TogetstartedwiththeGoogleMapsAPI,headoverto

http://code.google.com/apis/maps/andclickon"Signupfora

GoogleMapsAPIkey."Readandagreetothetermsofservice

(ifyoudoagree),enteryourhomepageaddress,andclick

GenerateAPIKey.Notonlywillyougetyourkeynow—don't

forgettomakeacopyofitforfutureuse—butGooglealso

offersyousomesamplemapcodetobeginwith.

Let'sanalyzethecode,shownhere:




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






GoogleMapsJavaScriptAPIExample


src="http://maps.google.com/maps?file=api&v=2&key=

type="text/javascript">



//
functionload(){

if(GBrowserIsCompatible()){

varmap=newGMap2(document.getElementById("map"));

map.setCenter(newGLatLng(37.4419,-122.1419),13);

}

}

//]]>

















ThisHTMLwilloutputablankpagewithnothingbutasmall

mapwidgetonit.IntheheadsectionoftheHTML,youwillsee

thattheGoogleMapsJavaScriptlibraryisreferenced(replace

"YOUR-KEY"withyouractualkeyvalue).Thebodyincludesa

divelement.InHTML,divisagenericdivisortowrapjust

aboutanythingyoucanthinkof;inthiscase,itwrapsamap.

Thebodyelementalsodefinesanonloadeventthatinvolves

thefunctionload(),whichrunsafterthepagefinishesloading

itsHTMLandimages.Intheload()function,youcanseethat

there'sasmallchecktoconfirmthatthebrowseriscompatible

withGoogleMapswidgets.Ifthatisthecase,anewmapobject

iscreated—itlooksforthepreviouslymentioneddivelement

withtheid"map"—andcenteredtoaspecificlatitude/longitude

location,withaspecificzoomlevel.

Sofar,there'snothinginthissamplethatanembeddingofa

simplemapinlineframe,asshownbefore,doesn'tachieveas

well.Butonceyouunderstandthisbasicexample,youcanadd

advancedfeaturesbyreadingthroughthetutorials,

documentationandexamplesavailableat

http://code.google.com/apis/maps/documentation/.

Forinstance,let'ssayyouwanttodropamarkerofyourown

onthemap.Belowthemap.setCenter()commandinthe

previousexample,youcanwritethefollowingJavaScripttodo

so:

varpoint=newGLatLng(37.4313,-122.1229);

map.addOverlay(newGMarker(point));



Orperhapsyouwanttoaddaninfowindowwhentheuser

clicksonthemap.Aso-calledeventlistenercanbedefinedfor

aresultliketheonepicturedinFigure11-7:

GEvent.addListener(map,"click",function(){

map.openInfoWindow(map.getCenter(),



document.createTextNode("Thanksforclicking!"));

});



TheGoogleMapsAPIin(sample)action



Becausetheseprogrammablewidgetscaninteractwithyour

ownsite'sdatainnewways,theyarealsocalled"maps

mashups."Onesuchmashupletsyoutrackthelocationofa

packageyouarewaitingfor[Hack#83].Othermashupsallow

youtocreateajogging/hikeroute,findskiresorts,measure

areas,lookupzipcodes,mapyourblogvisitors'locations,find

outwherethesunisshiningrightnow(asshowninFigure118),andmuchmore.Foramultitudeofmashupslikethese,take

alookat"100ThingstodowithGoogleMapsMashups"at

http://gmapsmania.googlepages.com/100thingstodowithgooglemapsmashu

Also,anotherO'Reillybook,GoogleMapsHacks(byRichGibson

andSchuylerErle,2006),presentsmanymorewaystoutilize

theGoogleMapsAPI.

Thehttp://daylightmap.comserviceshowsthemoving

daylightzones



Hack116.AddaGadgettoGoogleMaps

ExpandthefunctionalityofGoogleMapsthroughmapplets.

A"mapplet"iswhatGooglecallsagadgetthatcanbeaddedto

GoogleMaps.Mappletstaketheoppositeapproachfrom

embeddingtheGoogleMapsAPIonyoursite[Hack#115];

insteadofputtingasmallGoogleMapsmaponyoursite,you

putasmallpartofyoursiteorserviceontoGoogleMaps.Users

canthensubscribetoyourmappletusingGoogleMaps'My

Mapstab.

Togetatasteofmapplets,youcansubscribetooneyourself.

PointyourbrowsertoGoogleMaps(http://maps.google.com)

andswitchtotheMyMapstabontop.Undertheheadline

"Featuredcontent,"checktheboxtitledDistanceMeasurement

Tool.Thistoolwillnowbeactivatedandyoucanclickanytwo

pointsonthemainmaptocalculatethedistanceusing

kilometersormiles,amongotherunits,includingsuchexotic

onesas"Babyloniantradecubit"or"Americanfootballfield."As

picturedinFigure11-9,IcanseethatI'mroughly3,992miles

awayfrommyeditorBrianJepson,whoworkswithmeonthis

bookusingGoogleDocs.



TheDistanceMeasurementToolmapplet



Youcanfindmoremappletsbyfollowingthe"Browsethe

directory"linkontopoftheMyMapstab.Notethatwithinthe

directory,youcanusetheAddbyURLlinknexttothesearch

boxtoincludemappletswhicharenotyetinthedirectory.

CreatingYourOwnMapplet

Howwouldyougoaboutwritingsuchamappletservice

yourself?MappletsareaspecialformofGoogleGadgets[Hack

#60]thatutilizetheGoogleMapsAPI[Hack#115],soyou

needtounderstandabitofbothofthesecomponents.Google

GadgetsareXMLfilesstoredonline,andaremadeupofHTML,

stylesheetdefinitions,andJavaScript;andinthecaseof

mapplets,thatJavaScriptmakesuseoftheGoogleMapsAPI

library.



NOTE

Nomatterwhereamappletwasoriginallystored,

Googlewillcopyittotheirowndomain,gmodules.com,

beforeshowingittotheuser;thiscachingwilllastfor

sometimeandwillkeeptheloadonyourserverlow.

Togetanimpressionofhowthisallfitstogether,runtheHello

WorldsamplemappletthatGoogleprovides.AtGoogleMaps,

clickonMyMaps,andthenclickthe"Browsethedirectory"link.

SwitchtothesectionDeveloperToolsontheleft,andaddthe

gadgetcalledMappletScratchPadbyclickingtheAddItto

Mapsbutton,aspicturedinFigure11-10.

ClickBacktoGoogleMapsontop,andyouwillnowseethatthe

MappletScratchPadisenabled.Dependingonyourscreen

resolution,thetextareaofthescratchpadmaybequitesmall,

soyoumaywanttocopythecodeintoyourowntexteditorfor

morecomfortableediting,thencopyitbackeachtimeyouwant

totestorsavethecode.

Atthefooterofthescratchpad,youwillfindalinklabeledHello



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

Hack 115. Drop a Google Map Onto Your Site

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

×