Geolocation: Displaying User or Device Position on Maps

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

This tutorial shows you how to display the geographic location of a user or device on a Google map, using your browser's HTML5 Geolocation feature along ... 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 RoutesAPI(Preview) 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 AdvancedMarkers(Preview) OverviewGetstartedCreateadefaultAdvancedMarkerBasicmarkercustomizationCreatemarkerswithgraphicsCreatemarkerswithcustomHTMLControlcollisionbehaviorandmarkervisibilityMakemarkersclickableandaccessible 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 RoutesAPI(Preview) 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 Geolocation:DisplayingUserorDevicePositiononMaps Stayorganizedwithcollections Saveandcategorizecontentbasedonyourpreferences. Overview ThistutorialshowsyouhowtodisplaythegeographiclocationofauserordeviceonaGoogle map,usingyourbrowser'sHTML5GeolocationfeaturealongwiththeMapsJavaScriptAPI. (Notethatthegeographiclocationofauserwillonlydisplayifheorshehasallowedlocation sharing.) Belowisamapthatcanidentifyyourpresentlocation. Thesamplebelowshowstheentirecodeyouneedtocreatethismap. TypeScript //Note:Thisexamplerequiresthatyouconsenttolocationsharingwhen //promptedbyyourbrowser.Ifyouseetheerror"TheGeolocationservice //failed.",itmeansyouprobablydidnotgivepermissionforthebrowserto //locateyou. letmap:google.maps.Map,infoWindow:google.maps.InfoWindow; functioninitMap():void{ map=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{ center:{lat:-34.397,lng:150.644}, zoom:6, }); infoWindow=newgoogle.maps.InfoWindow(); constlocationButton=document.createElement("button"); locationButton.textContent="PantoCurrentLocation"; locationButton.classList.add("custom-map-control-button"); map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton); locationButton.addEventListener("click",()=>{ //TryHTML5geolocation. if(navigator.geolocation){ navigator.geolocation.getCurrentPosition( (position:GeolocationPosition)=>{ constpos={ lat:position.coords.latitude, lng:position.coords.longitude, }; infoWindow.setPosition(pos); infoWindow.setContent("Locationfound."); infoWindow.open(map); map.setCenter(pos); }, ()=>{ handleLocationError(true,infoWindow,map.getCenter()!); } ); }else{ //Browserdoesn'tsupportGeolocation handleLocationError(false,infoWindow,map.getCenter()!); } }); } functionhandleLocationError( browserHasGeolocation:boolean, infoWindow:google.maps.InfoWindow, pos:google.maps.LatLng ){ infoWindow.setPosition(pos); infoWindow.setContent( browserHasGeolocation ?"Error:TheGeolocationservicefailed." :"Error:Yourbrowserdoesn'tsupportgeolocation." ); infoWindow.open(map); } declareglobal{ interfaceWindow{ initMap:()=>void; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript //Note:Thisexamplerequiresthatyouconsenttolocationsharingwhen //promptedbyyourbrowser.Ifyouseetheerror"TheGeolocationservice //failed.",itmeansyouprobablydidnotgivepermissionforthebrowserto //locateyou. letmap,infoWindow; functioninitMap(){ map=newgoogle.maps.Map(document.getElementById("map"),{ center:{lat:-34.397,lng:150.644}, zoom:6, }); infoWindow=newgoogle.maps.InfoWindow(); constlocationButton=document.createElement("button"); locationButton.textContent="PantoCurrentLocation"; locationButton.classList.add("custom-map-control-button"); map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton); locationButton.addEventListener("click",()=>{ //TryHTML5geolocation. if(navigator.geolocation){ navigator.geolocation.getCurrentPosition( (position)=>{ constpos={ lat:position.coords.latitude, lng:position.coords.longitude, }; infoWindow.setPosition(pos); infoWindow.setContent("Locationfound."); infoWindow.open(map); map.setCenter(pos); }, ()=>{ handleLocationError(true,infoWindow,map.getCenter()); } ); }else{ //Browserdoesn'tsupportGeolocation handleLocationError(false,infoWindow,map.getCenter()); } }); } functionhandleLocationError(browserHasGeolocation,infoWindow,pos){ infoWindow.setPosition(pos); infoWindow.setContent( browserHasGeolocation ?"Error:TheGeolocationservicefailed." :"Error:Yourbrowserdoesn'tsupportgeolocation." ); infoWindow.open(map); } window.initMap=initMap;index.js Note:TheJavaScriptiscompiledfromtheTypeScriptsnippet. Viewexample TrySample Stackblitz.com CodeSandbox.io JSFiddle.net GitPod.io GoogleCloudShell WhatisGeolocation? Geolocationreferstotheidentificationofthegeographiclocationofauserorcomputingdevice viaavarietyofdatacollectionmechanisms.Typically,mostgeolocationservicesusenetwork routingaddressesorinternalGPSdevicestodeterminethislocation.Geolocationisa device-specificAPI.Thismeansthatbrowsersordevicesmustsupportgeolocationinordertouse itthroughwebapplications. W3CGeolocationstandard Applicationsthatwanttoperformgeolocationmustsupportthe W3CGeolocationstandard.Noticethatthe samplecodeabovedeterminestheuser'slocationthroughtheW3C navigator.geolocationproperty. SomebrowsersuseIPaddressestodetectauser'slocation.However,itmayonlyprovidearough estimateofauser'slocation.TheW3Capproachistheeasiestandmostfully-supportedsoit shouldbeprioritizedoverothergeolocationmethods. Sendfeedback Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2022-10-10UTC. [{ "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 Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文–简体 中文–繁體 日本語 한국어



請為這篇文章評分?