Overview | Maps JavaScript API - Google Developers

文章推薦指數: 80 %
投票人數:10人

function initMap(): void { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); Google MapsPlatform Overview Products Pricing Documentation GetStarted GetStartedwithGoogleMapsPlatform APIPicker Billing&Pricing Reporting&Monitoring MapIDs FAQ SupportandResources IncidentManagement Maps MapsJavaScriptAPI MapsSDKforAndroid MapsSDKforiOS MapsStaticAPI StreetViewStaticAPI MapsEmbedAPI MapsURLs MapsElevationAPI Routes DirectionsAPI DistanceMatrixAPI RoadsAPI Solutions IndustrySolutions GamingServices TransportationandLogistics Places PlacesAPI PlacesSDKforAndroid PlacesSDKforiOS PlacesLibrary,MapsJavaScriptAPI GeocodingAPI GeolocationAPI TimeZoneAPI AdditionalResources APISecurityBestPractices MapCoverageDetails OptimizationGuide MobileOSandsoftwaresupport Launchstages Deprecations AssetTrackingPlan URLEncoding WordPressUsers Blog Community StackOverflow GitHub YouTube Discord Twitter IssueTracker English BahasaIndonesia Deutsch Español Español–AméricaLatina Français Italiano Polski Português–Brasil TiếngViệt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文–简体 中文–繁體 日本語 한국어 Signin Web MapsJavaScriptAPI GetStarted Contactsales Guides Reference Samples Support Google MapsPlatform Overview Products Pricing Documentation More Guides Reference Samples Support Blog Community More MapsJavaScriptAPI Overview SetupinCloudConsole UsingAPIKeys Tutorials Alltutorials Addamarkertoyourmap Clustermarkers Real-timecollaborativemapping Showcurrentlocation Usedatawithyourmap DisplayingKMLImportingJSONdataVisualizingJSONdataCombiningJSONdata AddingaMapandMarkerstoaReactApplication Concepts Allconcepts Maptypes Mapandtilecoordinates Localizingthemap Versioning URLparameters Bestpractices UsingTypeScript Promises Managemarkerlabelcollisions Customizeamap CustomizewithCloud-basedmapsstyling OverviewMapStyleEditorwalkthroughManagemapstylesWorkwithzoomlevelsCustomizePOIbehaviorCustomizebuildingstyleStylingexamplesDesignchecklist CustomizewithJSONstyling JSONstylingoverviewJSONstylereference CustomLegends Interactwiththemap Controls Events Controlzoomandpan Drawonthemap Overview Markers Custommarkers Infowindows Shapes Symbols WebGLFeatures OverviewSupportVectorMapsTiltandRotationWebGLOverlayView Deck.gldatavisualizations Groundoverlays Customoverlays Displaydata Overview Data-drivenstyling(Preview) OverviewGetstartedStyleaboundarypolygonMakeachoroplethmapHandleclickeventsUsetheRegionLookupAPIUsetheRegionLookupAPIwithGoogleSheetsUseGeocodingandPlacesAPIswithData-drivenstylingGoogleboundariescoverage Datalayer Heatmap KMLandGeoRSS Traffic,Transit,andBicyclingLayers Services Directions DistanceMatrix Elevation Geocoding MaximumZoomImagery StreetView Libraries Overview DrawingLibrary GeometryLibrary LocalContextLibrary(Beta) OverviewGetStartedSettingLocalContextandMapOptionsHandlingEventsandUserInteractionRefreshingSearchPropertiesStylingtheLocalContextMapViewSupportedPlaceTypesMigratingaMaptoLocalContextMapView PlacesLibrary PlaceAutocomplete VisualizationLibrary OpenSourceLibraries MoreGuides ContentSecurityPolicyGuide GoogleLoaderMigrationGuide PlaceFieldMigration(open_now,utc_offset) PlaceDataFields PlaceIcons PlaceIDs PlaceTypes Upgradingfromv2tov3 PoliciesandTerms Usageandbilling Reportingandmonitoring Termsofservice OtherAPIs MapsStaticAPI StreetViewStaticAPI MapsEmbedAPI MapsURLs GetStarted GetStartedwithGoogleMapsPlatform APIPicker Billing&Pricing Reporting&Monitoring MapIDs FAQ SupportandResources IncidentManagement Maps MapsJavaScriptAPI MapsSDKforAndroid MapsSDKforiOS MapsStaticAPI StreetViewStaticAPI MapsEmbedAPI MapsURLs MapsElevationAPI Routes DirectionsAPI DistanceMatrixAPI RoadsAPI Solutions IndustrySolutions GamingServices TransportationandLogistics Places PlacesAPI PlacesSDKforAndroid PlacesSDKforiOS PlacesLibrary,MapsJavaScriptAPI GeocodingAPI GeolocationAPI TimeZoneAPI AdditionalResources APISecurityBestPractices MapCoverageDetails OptimizationGuide MobileOSandsoftwaresupport Launchstages Deprecations AssetTrackingPlan URLEncoding WordPressUsers StackOverflow GitHub YouTube Discord Twitter IssueTracker Home Products GoogleMapsPlatform Documentation Web MapsJavaScriptAPI Sendfeedback Overview Stayorganizedwithcollections Saveandcategorizecontentbasedonyourpreferences. Selectplatform: Android iOS JavaScript Beforeyoubegin: BeforeyoustartusingtheMapsJavaScriptAPI,youneedaprojectwithabillingaccountandthe MapsJavaScriptAPI enabled.WerecommendcreatingmultipleProjectOwnersandBillingAdministrators,sothat you'llalwayshavesomeonewiththeserolesavailabletoyourteam.Tolearnmore,see SetupinCloudConsole. TheMapsJavaScriptAPIletsyoucustomizemapswithyourowncontentand imageryfordisplayonwebpagesandmobiledevices.TheMapsJavaScriptAPI featuresfourbasicmaptypes(roadmap,satellite,hybrid,andterrain)whichyoucan modifyusinglayersandstyles,controlsandevents,andvariousservicesandlibraries. Audience Thisdocumentationisdesignedforpeoplefamiliarwith JavaScriptprogrammingandobject-orientedprogrammingconcepts.You shouldalsobefamiliarwithGoogle Mapsfromauser'spointofview.Therearemany JavaScript tutorialsavailableontheWeb. Thisconceptualdocumentationisdesignedtoletyouquicklystart exploringanddevelopingapplicationswiththeMapsJavaScriptAPI.Wealso publishtheMapsJavaScriptAPIReference. Hello,World TheeasiestwaytostartlearningabouttheMapsJavaScriptAPI istoseeasimpleexample.Thefollowingexampledisplaysamapcenteredon Sydney,NewSouthWales,Australia. TypeScript letmap:google.maps.Map; functioninitMap():void{ map=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{ center:{lat:-34.397,lng:150.644}, zoom:8, }); } declareglobal{ interfaceWindow{ initMap:()=>void; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript letmap; functioninitMap(){ map=newgoogle.maps.Map(document.getElementById("map"),{ center:{lat:-34.397,lng:150.644}, zoom:8, }); } window.initMap=initMap;index.js Note:TheJavaScriptiscompiledfromtheTypeScriptsnippet. CSS /* *Alwayssetthemapheightexplicitlytodefinethesizeofthedivelement *thatcontainsthemap. */ #map{ height:100%; } /* *Optional:Makesthesamplepagefillthewindow. */ html, body{ height:100%; margin:0; padding:0; } style.css HTML

SimpleMap index.html Viewexample TrySample Stackblitz.com CodeSandbox.io JSFiddle.net GitPod.io GoogleCloudShell Eveninthissimpleexample,thereareafewthingstonote: WedeclaretheapplicationasHTML5usingthedeclaration. Wecreateadivelementnamed"map"toholdthe map. WedefineaJavaScriptfunctionthatcreatesamapinthe div. WeloadtheMapsJavaScriptAPIusingascripttag. Thesestepsareexplainedbelow. DeclaringyourapplicationasHTML5 WerecommendthatyoudeclareatrueDOCTYPE withinyourwebapplication.Withintheexampleshere,we've declaredourapplicationsasHTML5usingthesimpleHTML5DOCTYPE asshownbelow: Mostcurrentbrowserswillrendercontentthatisdeclaredwiththis DOCTYPEin"standardsmode"whichmeansthatyourapplication shouldbemorecross-browsercompliant.TheDOCTYPEisalso designedtodegradegracefully;browsersthatdon'tunderstanditwillignore it,anduse"quirksmode"todisplaytheircontent. NotethatsomeCSSthatworkswithinquirksmodeisnotvalidin standardsmode.Inspecific,allpercentage-basedsizesmustinherit fromparentblockelements,andifanyofthoseancestorsfailto specifyasize,theyareassumedtobesizedat0x0pixels.For thatreason,weincludethefollowing ThisCSSdeclarationindicatesthatthemapcontainer
(withidmap)shouldtakeup100%oftheheightoftheHTML body.Notethatwemustspecificallydeclarethosepercentagesfor andaswell. LoadingtheMapsJavaScriptAPI TheMapsJavaScriptAPIisloadedusingascripttag,whichcanbeadded inlineinyourHTMLfileordynamicallyusingaseparateJavaScriptfile.Werecommendthatyou reviewbothapproaches,andchoosetheonethatismostappropriateforhowthecodeinyourproject isstructured. InlineLoading ToloadtheMapsJavaScriptAPIinlineinanHTMLfile,adda scripttagasshowbelow. DynamicLoading TodynamicallyloadtheMapsJavaScriptAPIinlineusingaseparateJavaScript file,seetheexamplebelow.Thisapproachallowsyoutohandleallofyourcodeforworking withtheAPIfromaseparate.jsfile,andistheequivalentofaddingthescript taginline. //Createthescripttag,settheappropriateattributes varscript=document.createElement('script'); script.src='https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap'; script.async=true; //Attachyourcallbackfunctiontothe`window`object window.initMap=function(){ //JSAPIisloadedandavailable }; //Appendthe'script'elementto'head' document.head.appendChild(script); DynamicLoading The@googlemaps/js-api-loaderpackageisavailabletomakeamoreseamlessdynamicloadingexperience.ItcanbeinstalledthroughNPMwiththefollowing: npminstall@googlemaps/js-api-loader Thispackagecanbeimportedintotheapplicationwith: import{Loader}from"@googlemaps/js-api-loader" TheloaderexposesaPromiseandcallbackinterface.ThefollowingdemonstratesusageofthedefaultPromisemethodload(). TypeScript constloader=newLoader({ apiKey:"YOUR_API_KEY", version:"weekly", ...additionalOptions, }); loader.load().then(()=>{ map=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{ center:{lat:-34.397,lng:150.644}, zoom:8, }); });index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript constloader=newLoader({ apiKey:"YOUR_API_KEY", version:"weekly", ...additionalOptions, }); loader.load().then(()=>{ map=newgoogle.maps.Map(document.getElementById("map"),{ center:{lat:-34.397,lng:150.644}, zoom:8, }); }); index.js ScriptTagAttributes Noticeintheexamplesabovethatseveralattributesaresetonthe scripttag,whicharerecommended.Thefollowingisanexplanation ofeachattribute. src:TheURLwheretheMapsJavaScriptAPIisloadedfrom, includingallofthesymbolsanddefinitionsyouneedforusingtheMapsJavaScriptAPI. TheURLinthisexamplehastwoparameters:key,whereyou provideyourAPIkey,andcallback,whereyouspecifythename ofaglobalfunctiontobecalledoncetheMapsJavaScriptAPI loadscompletely.ReadmoreaboutURLparameters. async:Asksthebrowsertoasynchronouslydownloadandexecute thescript.Whenthescriptisexecuted,itwillcallthefunctionspecified usingthecallbackparameter. Libraries WhenloadingtheMapsJavaScriptAPIviatheURLyoumayoptionally loadadditionallibrariesthroughuseofthe librariesURLparameter.Librariesaremodulesofcodethat provideadditionalfunctionalitytothemainMapsJavaScriptAPIbutarenot loadedunlessyouspecificallyrequestthem.Formore information,see LibrariesintheMapsJavaScriptAPI. SynchronouslyloadingtheAPI InthescripttagthatloadstheMapsJavaScriptAPI, itispossibletoomitthedeferattributeandthecallback parameter.ThiswillcausetheloadingoftheAPItoblockuntiltheAPIis downloaded. Thiswillprobablyslowyourpageload.Butitmeansyoucanwrite subsequentscripttagsassumingthattheAPIisalreadyloaded. Important:Consultthe ContentSecurityPolicy guidetolearnmoreaboutconfiguringCSPfortheMapsJavaScriptAPI. MapDOMElements
Forthemaptodisplayonawebpage,wemustreserveaspotforit. Commonly,wedothisbycreatinganameddivelementand obtainingareferencetothiselementinthebrowser'sdocumentobjectmodel (DOM). Intheexampleabove,weusedCSStosettheheightofthemapdivto "100%".Thiswillexpandtofitthesizeonmobiledevices.Youmayneedto adjustthewidthandheightvaluesbasedonthebrowser'sscreensizeand padding.Notethatdivsusuallytaketheirwidthfromtheircontaining element,andemptydivsusuallyhave0height.Forthisreason,youmust alwayssetaheightonthe
explicitly. MapOptions Therearetworequiredoptionsforeverymap:centerand zoom. map=newgoogle.maps.Map(document.getElementById('map'),{ center:{lat:-34.397,lng:150.644}, zoom:8 }); ZoomLevels Theinitialresolutionatwhichtodisplaythemapissetbythe zoomproperty,wherezoom0 correspondstoamapoftheEarthfullyzoomedout,andlargerzoomlevels zoominatahigherresolution. zoom:8 OfferingamapoftheentireEarthasasingleimagewouldeither requireanimmensemap,orasmallmapwithverylowresolution.As aresult,mapimageswithinGoogleMapsandtheMapsJavaScriptAPI arebrokenupintomap"tiles"and"zoomlevels."Atlowzoomlevels,asmallsetof maptilescoversawidearea;athigherzoomlevels,thetilesareof higherresolutionandcoverasmallerarea.Thefollowinglistshowsthe approximatelevelofdetailyoucanexpecttoseeateachzoomlevel: 1:World 5:Landmass/continent 10:City 15:Streets 20:Buildings ThefollowingthreeimagesreflectthesamelocationofTokyo atzoomlevels0,7and18. ForinformationonhowtheMapsJavaScriptAPIloads tilesbasedonthecurrentzoomlevel,seetheguideto mapand tilecoordinates. TheMapObject map=newgoogle.maps.Map(document.getElementById("map"),{...}); TheJavaScriptclassthatrepresentsamapistheMapclass. Objectsofthisclassdefineasinglemaponapage.(Youmaycreatemore thanoneinstanceofthisclass—eachobjectwilldefineaseparate maponthepage.)WecreateanewinstanceofthisclassusingtheJavaScript newoperator. Whenyoucreateanewmapinstance,youspecifya
HTMLelementinthepageasacontainerforthemap.HTMLnodes arechildrenoftheJavaScriptdocumentobject,and weobtainareferencetothiselementviathe document.getElementById()method. Thiscodedefinesavariable(namedmap)andassignsthat variabletoanewMapobject.ThefunctionMap()is knownasaconstructoranditsdefinitionisshownbelow: Constructor Description Map(mapDiv:Node,opts?:MapOptions ) CreatesanewmapinsideofthegivenHTMLcontainer—whichis typicallyaDIVelement—usingany(optional)parametersthat arepassed. Troubleshooting Reminder:TousetheMapsJavaScriptAPI: AllMapsJavaScriptAPIrequestsmustincludeanAPIkey; wenolongersupportkeylessaccess. Youmust enablebillingoneachofyourprojects. APIKeyandBillingErrors Undercertaincircumstances,adarkenedmap,or'negative'StreetViewimage, watermarkedwiththetext"fordevelopmentpurposesonly",maybedisplayed. ThisbehaviortypicallyindicatesissueswitheitheranAPIkeyorbilling. InordertouseGoogleMapsPlatformproducts,billingmustbeenabledonyouraccount, andallrequestsmustincludeavalidAPIkey.Thefollowingflowwillhelptroubleshootthis: AreyouusinganAPIkey? I'mnotsure.HowcanIcheckifIamusinganAPIkey? AnAPIkeyispassedasthekeyparameterintheURLthatisusedtoloadthe MapsJavaScriptAPI.HereareafewoptionstocheckifyouareusinganAPIkey: Usethe GoogleMapsPlatformAPICheckerChromeextension.Thisallowsyoutodetermineifyour websiteisproperlyimplementingGoogle’slicensedMapsAPIs. IfyouareusingalibraryorplugintoloadtheMapsJavaScriptAPI, checkthesettingsforthatlibraryandlookforanAPIkeyoption. Checkerrorsinyourbrowser. Ifyouseethefollowingmessages,youarenotusingyourAPIkeycorrectly: GoogleMapsJavaScriptAPIwarning: NoApiKeys GoogleMapsJavaScriptAPIerror: MissingKeyMapError Forwebdevelopers: Ifyouhaveaccesstothesourcecodeofyourapplication,lookforthe Checkthenetworktrafficgeneratedbyyourwebsiteinthebrowser. InChrome,thiscanbeviewedusingthe DevToolsNetworktab. Hereyouwillseethenetworkrequestsmadebyyourwebsite.Requestsmadeusingthe MapsJavaScriptAPIwillbeunderthepathmaps/api/js. Hereyoucanconfirmiftherequestsareusingthekeyparameter. Itmaybehelpfulto filteryournetworktrafficbymaps/api/jswhenviewingtheNetworktab. No,IamnotusinganAPIkey. TogetanAPIkey,clickthebuttonbelow.Ifyoudonotseeaguidedsetup,followthe fullinstructionsatGetStartedwithGoogleMaps Platform. GetStarted Yes,IamusinganAPIkey. Great!Let’smoveonandcheckifabillingaccountisattachedtoyourproject. Isabillingaccountattachedtoyourproject? I'mnotsure.HowcanIcheckifbillingaccountisattachedtomyproject? Gotothe BillingpageintheGoogleCloudConsoleandselecttheprojectunderwhichyourAPIkeywascreated. Toconfirmthekeyisassociatedwiththeproject: GototheCredentialssection,whichcanbeaccessedfromtheleftsidebarunder GoogleMapsPlatform>Credentials. CheckthattheAPIkeyyoucurrentlyuseonyourwebsiteislisted. Ifthat'snotthecase,switchtoadifferentproject,andcheckthecredentialsthere. IfyoucannotlocatetheprojectforyourAPIkey,youmayhavelostaccesstothisproject. Askothersinyourorganizationforhelp.Iftheoriginalprojectcannotbelocated,youshould: Createanewproject.ThiscanbedonebyselectingNewProject fromtheprojectslist,orbyselectingCreateProjectviathe ResourceManagerpage. CreateanewAPIkey.ThiscanbedoneontheCredentialspage. OncethereclickCreatecredentialsandthenselectAPIkey. OnceyouhavelocatedyourprojectintheCloudConsole, checkifabillingaccountisattachedbynavigatingtotheBillingsectionintheleftsidemenu. No,abillingaccountisnotattachedtomyproject. GototheEnableBillingpageintheCloudConsole andaddabillingaccounttoyourproject.Foradditionalinformation,see GetStartedwithGoogleMapsPlatform. Yes,abillingaccountisattachedtomyproject. Great!Let’smakesuretheprovidedbillingmethodisvalid. Istheprovidedbillingmethodnolongervalid(forexampleanexpiredcreditcard)? You canadd,remove,orupdateapaymentmethodintheCloudConsole. Isthereanexceededself-imposeddailylimitontheAPI? IfyouhavesetadailylimitonanyofyourAPIs,whichiscommontopreventunexpectedincreases, youcanresolvethisbyincreasingyourdailylimit. Youcancheckyourdailylimitsbygoingtothe APIs&ServicesDashboardinthe CloudConsole.Oncethere: Selectaprojectifprompted. SelectanAPIfromthelist,thenclicktheQuotastab. DoesyourAPIkeyhaveanIPaddressesrestriction? APIkeyswithanIPaddressesrestrictioncanonlybeusedwithwebservicesthatare intendedforusefromtheserverside(suchasthe GeocodingAPI andotherWebServiceAPIs). MostofthesewebserviceshaveequivalentserviceswithintheMapsJavaScriptAPI(forexample,seethe GeocodingService). TousetheMapsJavaScriptAPIclientsideservices,youwillneedtocreateaseparateAPIkeywhich canbesecuredwithanHTTPreferrersrestriction(see Get,add,andrestrictanAPIkey). Ifyourcodeisn'tworking: Tohelpyougetyourmapscodeupandrunning,BrendanKennyandManoMarkspointout somecommonmistakesandhowtofixtheminthisvideo. Lookfortypos.RememberthatJavaScriptisacase-sensitive language. Checkthebasics-someofthemostcommonproblemsoccurwiththe initialmapcreation.Suchas: Confirmthatyou'vespecifiedthezoom andcenterpropertiesinyourmap options. Ensurethatyouhavedeclaredadivelementinwhichthemapwill appearonthescreen. Ensurethatthedivelementforthemaphasaheight.Bydefault, divelementsarecreatedwithaheightof0,andaretherefore invisible. Refertoourexamplesfora reference implementation. UseaJavaScriptdebuggertohelpidentifyproblems,liketheoneavailable intheChrome DeveloperTools.StartbylookingintheJavaScriptconsoleforerrors. PostquestionstoStack Overflow.Guidelinesonhowtopostgreatquestionsareavailableon theSupportpage. Sendfeedback Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2022-09-21UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] Needtotellusmore? StackOverflow Askaquestionunderthegoogle-mapstag. GitHub Forkoursamplesandtrythemyourself. Discord ChatwithfellowdevelopersaboutGoogleMapsPlatform. IssueTracker Somethingwrong?Sendusabugreport! LearnMore FAQ APIPicker Tutorials Platforms Android iOS Web WebServices ProductInfo PricingandPlans ContactSales Support TermsofService Android Chrome Firebase GoogleCloudPlatform Allproducts Terms Privacy SignupfortheGoogleDevelopersnewsletter Subscribe English BahasaIndonesia Deutsch Español Español–AméricaLatina Français Italiano Polski Português–Brasil TiếngViệt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文–简体 中文–繁體 日本語 한국어


請為這篇文章評分?