Overview | Geolocation API | Google Developers
文章推薦指數: 80 %
The Geolocation API returns a location and accuracy radius based on information about cell towers and WiFi nodes that the mobile client can detect. 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 Français Italiano Polski Português–Brasil TiếngViệt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文–简体 中文–繁體 日本語 한국어 Signin WebServices GeolocationAPI GetStarted Contactsales Guides Support Google MapsPlatform Overview Products Pricing Documentation More Guides Support Blog Community More Overview Setup SetupinCloudConsole UsingAPIKeys BestPractices WebServiceBestPractices BillingandReporting UsageandBilling ReportingandMonitoring PoliciesandTerms Policies TermsofService OtherAPIs DirectionsAPI DistanceMatrixAPI ElevationAPI GeocodingAPI PlacesAPI RoadsAPI TimeZoneAPI 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 WebServices GeolocationAPI Guides Sendfeedback Overview Stayorganizedwithcollections Saveandcategorizecontentbasedonyourpreferences. Beforeyoubegin: BeforeyoustartusingtheGeolocationAPI,youneedaprojectwithabillingaccountandthe GeolocationAPI enabled.WerecommendcreatingmultipleProjectOwnersandBillingAdministrators,sothat you'llalwayshavesomeonewiththeserolesavailabletoyourteam.Tolearnmore,see SetupinCloudConsole. Introduction TheGeolocationAPIreturnsalocationandaccuracyradius basedoninformationaboutcelltowersandWiFinodesthatthemobileclient candetect.Thisdocumentdescribestheprotocolusedtosendthisdatato theserverandtoreturnaresponsetotheclient. CommunicationisdoneoverHTTPSusingPOST.Bothrequestandresponseare formattedasJSON,andthecontenttypeofbothis application/json. Beforeyoubegin BeforeyoustartdevelopingwiththeGeolocationAPI, reviewtheauthentication requirements(youneedanAPIkey)andthe APIusageandbilling information(youneedtoenablebillingonyourproject). Geolocationrequests GeolocationrequestsaresentusingPOSTtothefollowingURL: https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY Youmustspecifyakeyinyourrequest,includedasthevalueofa keyparameter.Akeyisyourapplication's APIkey.Thiskeyidentifiesyourapplicationforpurposesofquota management.Learnhowtogetakey. Requestbody TherequestbodymustbeformattedasJSON.Iftherequestbodyisnotincluded,theresults willbereturnedbasedontheIPaddressofrequestlocation.Thefollowingfieldsare supported,andallfieldsareoptional,unlessotherwisestated: Field JSONtype Description Notes homeMobileCountryCode number(uint32) Themobilecountrycode(MCC)forthedevice'shomenetwork. SupportedforradioTypegsm(default), wcdma,lteandnr;notusedforcdma. Validrange:0–999. homeMobileNetworkCode number(uint32) TheMobileNetworkCodeforthedevice'shomenetwork. ThisistheMNCforGSM,WCDMA,LTEandNR. CDMAusestheSystemID(SID) ValidrangeforMNC:0–999. ValidrangeforSID:0–32767. radioType string Themobileradiotype.Supportedvaluesaregsm,cdma, wcdma,lteandnr. Whilethisfieldisoptional,itshouldalwaysbeincludediftheradiotypeis knownbytheclient. Ifthefieldisomitted,GeolocationAPIwilldefaulttogsm, whichwillresultininvalidorzeroresultsiftheassumedradiotypeis incorrect. carrier string Thecarriername. considerIp boolean SpecifieswhethertofallbacktoIPgeolocationifWiFiandcelltowersignalsaremissing, empty,ornotsufficienttoestimatedevicelocation. Defaultstotrue.SetconsiderIptofalsetodisable fallback. cellTowers array Anarrayofcelltowerobjects. SeetheCellTowerObjectssectionbelow. wifiAccessPoints array AnarrayofWiFiaccesspointobjects. SeetheWiFiAccessPointObjectssection below. AnexampleGeolocationAPIrequestbodyisshownbelow. { "homeMobileCountryCode":310, "homeMobileNetworkCode":410, "radioType":"gsm", "carrier":"Vodafone", "considerIp":true, "cellTowers":[ //SeetheCellTowerObjectssectionbelow. ], "wifiAccessPoints":[ //SeetheWiFiAccessPointObjectssectionbelow. ] } Celltowerobjects Therequestbody'scellTowersarraycontainszeroormore celltowerobjects. Field JSONtype Description Notes cellId number(uint32) Uniqueidentifierofthecell. RequiredforradioTypegsm(default),cdma, wcdmaandlte;rejectedfornr. SeetheCalculatingcellIdsectionbelow,whichalsolists thevalidvaluerangesforeachradiotype. newRadioCellId number(uint64) UniqueidentifieroftheNR(5G)cell. RequiredforradioTypenr;rejectedforother types. SeetheCalculatingnewRadioCellIdsectionbelow, whichalsoliststhevalidvaluerangeforthefield. locationAreaCode number(uint32) TheLocationAreaCode(LAC)forGSMandWCDMAnetworks. TheNetworkID(NID)forCDMAnetworks. TheTrackingAreaCode(TAC)forLTEandNRnetworks. RequiredforradioTypegsm(default)and cdma,optionalforothervalues. Validrangewithgsm,cdma,wcdmaand lte:0–65535. Validrangewithnr:0–16777215. mobileCountryCode number(uint32) Thecelltower'sMobileCountryCode(MCC). RequiredforradioTypegsm(default),wcdma, lteandnr;notusedforcdma. Validrange:0–999. mobileNetworkCode number(uint32) Thecelltower'sMobileNetworkCode. ThisistheMNCforGSM,WCDMA,LTEandNR. CDMAusestheSystemID(SID). Required. ValidrangeforMNC:0–999. ValidrangeforSID:0–32767. Thefollowingoptionalfieldsarenotcurrentlyused,butmaybeincludedifvaluesare available. Field JSONtype Description Notes age number(uint32) Thenumberofmillisecondssincethiscellwasprimary. Ifageis0,thecellIdornewRadioCellIdrepresentsacurrent measurement. signalStrength number(double) RadiosignalstrengthmeasuredindBm. timingAdvance number(double) The timingadvance value. CalculatingcellId RadiotypespriortoNR(5G)usethe32-bitcellIdfieldforpassingthenetwork cellIDtoGeolocationAPI. GSM(2G)networksusethe16-bitCellID(CID)asis.Validrange:0–65535. CDMA(2G)networksusethe16-bitBaseStationID(BID)asis.Validrange:0–65535. WCDMA(3G)networksusetheUTRAN/GERANCellIdentity(UC-ID),whichisa28-bitinteger valueconcatenatingthe12-bitRadioNetworkControllerIdentifier(RNC-ID)and16-bit CellID(CID). Formula:rnc_id<<16|cid. Validrange:0–268435455. Note:Specifyingonlythe16-bitCellIDvalueinWCDMAnetworkswillresultin incorrectorzeroresults. LTE(4G)networksusetheE-UTRANCellIdentity(ECI),whichisa28-bitintegervalue concatenatingthe20-bitE-UTRANNodeBIdentifier(eNBId)andthe8-bitCellID(CID). Formula:enb_id<<8|cid. Validrange:0–268435455. Note:Specifyingonlythe8-bitCellIDvalueinLTEnetworkswillresultin incorrectorzeroresults. PlacingvaluesoutsidetheserangesintheAPIrequestmayresultinundefinedbehavior.TheAPI, atGoogle'sdiscretion,maytruncatethenumbersoitfitsinthedocumentedrange,infera correctiontotheradioType,orreturnaNOT_FOUNDresultwithoutany indicatorintheresponse. AnexampleLTEcelltowerobjectisbelow. { "cellTowers":[ { "cellId":170402199, "locationAreaCode":35632, "mobileCountryCode":310, "mobileNetworkCode":410, "age":0, "signalStrength":-60, "timingAdvance":15 } ] } CalculatingnewRadioCellId Newernetworks,whosecellIDsarelongerthan32bitsusethe64-bit newRadioCellIdfieldforpassingthenetworkcellIDto GeolocationAPI. NR(5G)networksusethe36-bitNewRadioCellIdentity(NCI)asis. Validrange:0–68719476735. AnexampleNRcelltowerobjectisbelow. { "cellTowers":[ { "newRadioCellId":68719476735, "mobileCountryCode":310, "mobileNetworkCode":410, "age":0, "signalStrength":-60, } ] } WiFiaccesspointobjects Therequestbody'swifiAccessPointsarraymustcontaintwo ormoreWiFiaccesspointobjects.macAddressisrequired;all otherfieldsareoptional. Field JSONtype Description Notes macAddress string TheMACaddressoftheWiFinode.It'stypicallycalledaBSS,BSSIDorMACaddress. Required.:(colon)separatedhexadecimalstring. signalStrength number(double) ThecurrentsignalstrengthmeasuredindBm. age number(uint32) Thenumberofmillisecondssincethisaccesspointwasdetected. channel number(uint32) Thechanneloverwhichtheclientiscommunicatingwiththeaccesspoint. signalToNoiseRatio number(double) Thecurrentsignaltonoiseratio measuredindB. AnexampleWiFiaccesspointobjectisshownbelow. { "macAddress":"9c:1c:12:b0:45:f1", "signalStrength":-43, "signalToNoiseRatio":0, "channel":11, "age":0 } Geolocationresponses AsuccessfulgeolocationrequestwillreturnaJSON-formattedresponse definingalocationandradius. location:Theuser’sestimatedlatitudeandlongitude,in degrees.Containsonelatandonelng subfield. accuracy:Theaccuracyoftheestimatedlocation,in meters.Thisrepresentstheradiusofacirclearoundthegiven location. { "location":{ "lat":37.421875199999995, "lng":-122.0851173 }, "accuracy":120 } Errors Inthecaseofanerror,astandardformaterrorresponsebodywillbe returnedandtheHTTPstatuscodewillbesettoanerrorstatus. Theresponsecontainsanobjectwithasingleerrorobjectwith thefollowingkeys: code:ThisisthesameastheHTTPstatusoftheresponse. message:Ashortdescriptionoftheerror. errors:Alistoferrorswhichoccurred.Eacherrorcontainsan identifierforthetypeoferror(thereason)andashortdescription (themessage). Forexample,sendinginvalidJSONwillreturnthefollowingerror: { "error":{ "errors":[ { "domain":"global", "reason":"parseError", "message":"ParseError", } ], "code":400, "message":"ParseError" } } Possibleerrorsinclude: Reason Domain HTTPStatusCode Description dailyLimitExceeded usageLimits 403 Youhaveexceededyourdailylimit. keyInvalid usageLimits 400 YourAPIkeyisnotvalidfortheGeolocationAPI.Pleaseensurethat you'veincludedtheentirekey,andthatyou'veeitherpurchasedtheAPI orhaveenabledbillingandactivatedtheAPItoobtainthequotaat nocharge. userRateLimitExceeded usageLimits 403 YouhaveexceededtherequestlimitthatyouconfiguredintheGoogleCloudConsole. Thislimitistypicallysetasrequestsperday,requestsper100seconds, andrequestsper100secondsperuser.Thislimitshouldbeconfigured topreventasingleorsmallgroupofusersfromexhaustingyourdailyquota, whilestillallowingreasonableaccesstoallusers. SeeCappingAPIUsage toconfiguretheselimits. notFound geolocation 404 Therequestwasvalid,butnoresultswerereturned. parseError global 400 TherequestbodyisnotvalidJSON.Refertothe RequestBodysectionfordetailsoneach field. Samplerequests Note:Macaddressescanchangeovertime. Forthatreason,theexamplesonthispagemayresultinanerrormessage fromtheAPI. Ifyou'dliketotrytheGeolocationAPIwithsampledata,save thefollowingJSONtoafile: { "considerIp":"false", "wifiAccessPoints":[ { "macAddress":"84:d4:7e:f6:99:64", "signalStrength":-54, "signalToNoiseRatio":0 }, { "macAddress":"84:d4:7e:f6:99:71", "signalStrength":-43, "signalToNoiseRatio":0 }, { "macAddress":"84:d4:7e:f7:21:35", "signalStrength":-32, "signalToNoiseRatio":0 } ] } YoucanthenusecURLtomakeyourrequest fromthecommandline: $curl-d@your_filename.json-H"Content-Type:application/json"-i"https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY" TheresponsefortheaboveMacaddresseslookslikethis: { "location":{ "lat":37.4237423, "lng":-122.0915814 }, "accuracy":20 } (SeeGetanAPIKeyifyoudon'thaveanAPIkey.) Foradditionaltesting,youcangatherinformationfromyourAndroiddeviceusingthe PlacesSDKforAndroidandthe Android LocationAPIs,andfromyouriOSdeviceusingthe PlacesSDKforiOS. Frequentlyaskedquestions WhyamIgettingaverylargeaccuracyradiusinmy Geolocationresponse? IfyourGeolocationresponseshowsaveryhighvalueinthe accuracyfield,theservicemaybegeolocatingbasedonthe requestIP,insteadofWiFipointsorcelltowers.Thiscanhappenifno celltowersoraccesspointsarevalidorrecognized. Toconfirmthatthisistheissue,setconsiderIpto falseinyourrequest.Iftheresponseisa404, you'veconfirmedthatyourwifiAccessPointsand cellTowersobjectscouldnotbegeolocated. 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 Français Italiano Polski Português–Brasil TiếngViệt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文–简体 中文–繁體 日本語 한국어
延伸文章資訊
- 1[30apis] Day 2 : Google Map Geolocation API - iT 邦幫忙
關於Geolocation 在實作之前,我大致上知道Google Map 有個定位的API (廢話)但我一直以為它叫做location API。 所以在這邊對Location 跟Geolo...
- 2茶米老師教室- Geolocation API - Google Sites
HTML5 提供了Geolocation API 讓瀏覽者可以由網頁中或是設備的GPS 取得目前的位置。在網頁中您可以使用navigator.geolocation 來測試目前的瀏覽器是否支援G...
- 3ipstack - Free IP Geolocation API
Locate website visitors for free using ipstack - a free, real-time IP address to location JSON AP...
- 4HTML5 Geolocation API - BrowserLeaks
The Geolocation API gives websites access to a high-level interface that allows them to query phy...
- 5Geolocation API - MDN Web Docs
The Geolocation API allows the user to provide their location to web applications if they so desi...