Geolocation API - W3C

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

The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation. Abstract TheGeolocationAPIprovidesaccesstogeographicallocation informationassociatedwiththehostingdevice. StatusofThisDocumentThissectiondescribesthestatusofthis documentatthetimeofitspublication.AlistofcurrentW3C publicationsandthelatestrevisionofthistechnicalreportcanbefound intheW3Ctechnicalreportsindexat https://www.w3.org/TR/. TheDevicesandSensorsWorkingGroupisupdatingthisspecificationin thehopeofmakingita"livingstandard".Assuch,we'vedroppedthe "Editions"andaimtocontinuepublishingupdatedW3CRecommendations ofthisspecificationasweaddnewfeaturesorfixbugs. ThisdocumentwaspublishedbytheDevicesandSensorsWorkingGroupas aRecommendationusingthe Recommendationtrack. W3Crecommendsthewidedeploymentofthisspecificationasastandardfor theWeb. AW3CRecommendationisaspecificationthat,afterextensive consensus-building,isendorsedby W3CanditsMembers,and hascommitmentsfromWorkingGroupmembersto royalty-freelicensing forimplementations. FutureupdatestothisRecommendationmayincorporate newfeatures. Thisdocumentwasproducedbyagroup operatingunderthe W3CPatent Policy. W3Cmaintainsa publiclistofanypatentdisclosures madeinconnectionwiththedeliverablesof thegroup;thatpagealsoincludes instructionsfordisclosingapatent.Anindividualwhohasactual knowledgeofapatentwhichtheindividualbelievescontains EssentialClaim(s) mustdisclosetheinformationinaccordancewith section6oftheW3CPatentPolicy. Thisdocumentisgovernedbythe 2November2021W3CProcessDocument. TableofContentsAbstractStatusofThisDocument1. Introduction 1.1 Scope 1.2 Changelog 2. Examples 2.1 Getcurrentposition 2.2 Watchaposition 2.3 Stopwatchingaposition 2.4 Handlingerrors 2.5 UsingmaximumAgeascachecontrol 2.6 Usingtimeout 2.7 EnablingtheAPIinthird-partycontexts 3. Privacyconsiderations 3.1 Userconsent 3.2 Privacyconsiderationsforrecipientsoflocationinformation 3.3 Implementationconsiderations 3.4 CheckingpermissiontousetheAPI 4. Securityconsiderations 5. ExtensionstotheNavigatorinterface 6. Geolocationinterfaceandcallbacks 6.1 Internalslots 6.2 getCurrentPosition()method 6.3 watchPosition()method 6.4 clearWatch()method 6.5 Requestaposition 6.6 Acquireaposition 6.7 Callbackwitherror 7. PositionOptionsdictionary 7.1 enableHighAccuracymember 7.2 timeoutmember 7.3 maximumAgemember 8. GeolocationPositioninterface 8.1 coordsattribute 8.2 timestampattribute 8.3 Internalslots 8.4 Tasksources 9. GeolocationCoordinatesinterface 9.1 latitude,longitude,andaccuracyattributes 9.2 altitudeandaltitudeAccuracyattributes 9.3 headingattribute 9.4 speedattribute 9.5 ConstructingaGeolocationPosition 10. GeolocationPositionErrorinterface 10.1 Constants 10.2 codeattribute 10.3 messageattribute 11. Permissionspolicy 12.ConformanceA.IDLIndexB.IndexB.1TermsdefinedbythisspecificationB.2TermsdefinedbyreferenceC. Acknowledgments D.ReferencesD.1NormativereferencesD.2Informativereferences 1. Introduction Thissectionisnon-normative. TheGeolocationAPIdefinesahigh-levelinterfaceto locationinformationassociatedonlywiththedevicehostingthe implementation.CommonsourcesoflocationinformationincludeGlobal PositioningSystem(GPS)andlocationinferredfromnetworksignals suchasIPaddress,RFID,WiFiandBluetoothMACaddresses,and GSM/CDMAcellIDs,aswellasuserinput.TheAPIitselfisagnosticof theunderlyinglocationinformationsources,andnoguaranteeisgiven thattheAPIreturnsthedevice'sactuallocation. Ifanendusergrantspermission,the GeolocationAPI: Provideslocationdataaslatitude,longitude,altitude,speed,and heading,aswellastheaccuracyoftheacquiredlocationdata,andthe approximatetimeforwhenthepositionwasacquiredviathe GeolocationPositioninterface. Supports"one-shot"positionupdatesviathe getCurrentPosition()methodandtheabilitytoreceive updatesforwhenthepositionofthehostingdevicesignificantly changesviathewatchPosition()method. UsingthePositionOptions'smaximumAge, allowsanapplicationtorequestacachedpositionwhoseageisno greaterthanaspecifiedvalue(onlythelastpositioniscached). Providesawayfortheapplicationtoreceiveupdatesabouterrors, asaGeolocationPositionError,thathaveoccurredwhileacquiringaposition. AndthroughenableHighAccuracy,supports requesting"highaccuracy"positiondata,thoughtherequestcanbe ignoredbytheuseragent. 1.1 Scope Thissectionisnon-normative. ThisspecificationislimitedtoprovidingascriptingAPIfor retrievinggeographicpositioninformationassociatedwithahosting device.Thegeographicpositioninformationisprovidedintermsof WorldGeodeticSystemcoordinates[WGS84].Itdoesnotinclude providingamarkuplanguageofanykind,nordoesnotinclude defininganewURLschemeforbuildingURLsthatidentifygeographic locations. 1.2 Changelog Thissectionisnon-normative. SinceFirstPublicWorkingDraftin2021,theGeolocation APIhasreceivedthefollowingnormativechanges: fix"Queueatask"/"inparallel"usage(#118)Suggestpermissionlifetime(#108)HandleOS-levelpermissionchange(#109)SwitchDOMTimeStamptoEpochTimeStamp(#104)Return0whenwatchPosition()errors(#100)Callbackwitherrorifdocisnotfullyactive(#97)Gracefullyhandledocumentsthatarenotfullyactive(#90)Add"geolocationtaskqueue"(#87) SincepublicationoftheSecondEditionin2016,thisspecification hasreceivedthefollowingchanges: Requestapositiononlyproceedswhenadocumentisvisible, orthedocumentbecomesvisible. Clarifiedhowcachingworksaspartofacquiringaposition: onlylastpositioniscached,andcanbeevictedatanytime. NowreliesonthePermissionsspecificationtohandle permissiongrants,anduserinterfacerequirements. TheerrorCallbackisnownullable. TheAPIcanbecontrolledbyPermissionsPolicy,which restrictshow/wheretheAPIisexposedtowebpages. Thecallbacksarenolongertreatedas"EventHandler"objects (i.e.,objectsthathavea.handleEvent()method),butarenow exclusivelytreatedasIDLcallbackfunctions. TheAPIisnowonlyexposedinSecureContexts(i.e.,only availableinHTTPS). Theinterfacesnolongeruse[WebIDL]'slegacy [NoInterfaceObject],soGeolocationandotherinterfaceofthis specarenowintheglobalscope.Also,theinterfaceswererenamed fromNavigatorGeolocation*tojustGeolocation*. Seethecommit historyforacompletelistofchanges. 2. Examples Thissectionisnon-normative. TheAPIisdesignedtoenableboth"one-shot"positionrequestsand repeatedpositionupdates.Thefollowingexamplesillustratecommonuse cases. 2.1 Getcurrentposition Thissectionisnon-normative. Requesttheuser'scurrentlocation.Iftheuserallowsit,youwill getbackapositionobject. Example1:Aone-shotpositionrequest navigator.geolocation.getCurrentPosition(position=>{ const{latitude,longitude}=position.coords; //Showamapcenteredatlatitude/longitude. }); 2.2 Watchaposition Thissectionisnon-normative. Requesttheabilitytowatchuser'scurrentlocation.Iftheuser allowsit,youwillgetbackcontinuousupdatesoftheuser's position. Example2:Watchingapositionforrepeatedupdates constwatchId=navigator.geolocation.watchPosition(position=>{ const{latitude,longitude}=position.coords; //Showamapcenteredatlatitude/longitude. }); 2.3 Stopwatchingaposition Thissectionisnon-normative. Stopwatchingforpositionchangesbycallingthe clearWatch()method. Example3:UsingclearWatch() constwatchId=navigator.geolocation.watchPosition( position=>console.log(position) ); functionbuttonClickHandler(){ //Canceltheupdateswhentheuserclicksabutton. navigator.geolocation.clearWatch(watchId); } AndaHTMLbuttonthatwhenpressedstopswatchingtheposition. Stopwatchinglocation 2.4 Handlingerrors Thissectionisnon-normative. Whenanerroroccur,thesecondargumentofthe watchPosition()or getCurrentPosition()methodgetscalledwitha GeolocationPositionErrorerror,whichcanhelpyoufigureout whatmighthavegonewrong. Example4:Handlingerrors //Requestrepeatedupdates. constwatchId=navigator.geolocation.watchPosition( scrollMap,handleError ); functionscrollMap(position){ const{latitude,longitude}=position.coords; //Scrollmaptolatitude/longitude. } functionhandleError(error){ //Displayerrorbasedontheerrorcode. const{code}=error; switch(code){ caseGeolocationPositionError.TIMEOUT: //Handletimeout. break; caseGeolocationPositionError.PERMISSION_DENIED: //Userdeniedtherequest. break; caseGeolocationPositionError.POSITION_UNAVAILABLE: //Positionnotavailable. break; } } 2.5 UsingmaximumAgeascachecontrol Thissectionisnon-normative. Bydefault,theAPIalwaysattemptstoreturnacachedpositionso longasithasapreviouslyacquiredposition.Inthisexample,we acceptapositionwhoseageisnogreaterthan10minutes.Ifthe useragentdoesnothaveafreshenoughcachedpositionobject,it automaticallyacquiresanewposition. Example5:Gettingcachedposition navigator.geolocation.getCurrentPosition( successCallback, console.error, {maximumAge:600_000} ); functionsuccessCallback(position){ //Byusingthe'maximumAge'memberabove,theposition //objectisguaranteedtobeatmost10minutesold. } 2.6 Usingtimeout Ifyourequirelocationinformationinatimesensitivemanner,you canusethePositionOptionstimeoutmemberto limittheamountoftimeyouarewillingtowaittoacquireaposition. Example6:Timingoutapositionrequest //Requestaposition.Weareonlywillingtowait10 //secondsforit. navigator.geolocation.getCurrentPosition( successCallback, errorCallback, {timeout:10_000} ); functionsuccessCallback(position){ //Requestfinishedinunder10seconds... } functionerrorCallback(error){ switch(error.code){ caseGeolocationPositionError.TIMEOUT: //Wedidn'tgetitinatimelyfashion. doFallback(); //Acquireanewpositionobject, //aslongasittakes. navigator.geolocation.getCurrentPosition( successCallback,errorCallback ); break; case"..."://treattheothererrorcases. } } functiondoFallback(){} 2.7 EnablingtheAPIinthird-partycontexts Thissectionisnon-normative. Thedefaultallowlistof'self'allowsGeolocationAPIusage insame-originnestedframesbutpreventsthird-partycontentfrom usingtheAPI. Third-partyusagecanbeselectivelyenabledbyaddingthe allow="geolocation"attributetoaniframeelement: Example7:EnablingtheGeolocationAPIinaniframe Alternatively,theAPIcanbedisabledinafirst-partycontextby specifyinganHTTPresponseheader: Example8:PermissionsPolicyoverHTTP Permissions-Policy:geolocation=() SeePermissionsPolicyformoredetailsaboutthe Permissions-PolicyHTTPheader. 3. Privacyconsiderations Thissectionisnon-normative. TheAPIdefinedinthisspecificationisusedtoretrievethe geographiclocationofahostingdevice.Inalmostallcases,this informationalsodisclosesthelocationoftheuserofthedevice, therebypotentiallycompromisingtheuser'sprivacy. 3.1 Userconsent Thissectionisnon-normative. TheGeolocationAPIisapowerfulfeaturethat requiresexpresspermissionfromanend-userbeforeanylocation dataissharedwithawebapplication.Thisrequirementis normativelyenforcedbythecheckpermissionstepsonwhichthe getCurrentPosition()and watchPosition()methodsrely. Anend-userwillgenerallygiveexpresspermissionthroughauser interface,whichusuallypresentarangeofpermission lifetimesthattheend-usercanchoosefrom.The choiceoflifetimesvaryacrossuseragents,butthey aretypicallytime-based(e.g.,"aday"),oruntilbrowserisclosed, ortheusermightevenbegiventhechoiceforthepermissiontobe grantedindefinitely.Thepermissionlifetimesdictate howlongauseragentgrantsapermissionbeforethat permissionisautomaticallyrevertedbacktoitsdefaultpermissionstate,promptingtheend-usertomakeanewchoiceuponsubsequent use. Althoughthegranularityofthepermissionlifetime variesacrossuser-agents,thisspecificationurgesuseragentsto limitthelifetimetoasinglebrowsingsessionbydefault(see 3.4 CheckingpermissiontousetheAPIfornormativerequirements). 3.2 Privacyconsiderationsforrecipientsoflocationinformation Thissectionisnon-normative. Note:Developers'responsibilitywiththissensitivedata Thissectionappliesto"recipients",whichgenerallymeans developersutilizingtheGeolocationAPI.Althoughit's impossiblefortheuseragent,orthisspecification,toenforce theserequirements,developersneedtoreadthissectioncarefully anddotheirbesttoadheretothesuggestionsbelow.Developersneed tobeawarethattheremightbeprivacylawsintheirjurisdictions thatcangoverntheusageandaccesstousers'locationdata. Recipientsoughttoonlyrequestpositioninformationwhennecessary, andonlyusethelocationinformationforthetaskforwhichitwas providedtothem.Recipientsoughttodisposeoflocationinformation oncethattaskiscompleted,unlessexpresslypermittedtoretainit bytheuser.Recipientsneedtoalsotakemeasurestoprotectthis informationagainstunauthorizedaccess.Iflocationinformationis stored,usersneedtobeallowedtoupdateanddeletethis information. Therecipientsoflocationinformationneedtorefrainfrom retransmittingthelocationinformationwithouttheuser’sexpress permission.Careneedstobetakenwhenretransmittingandtheuseof encryptionisencouraged. Recipientsoughttoclearlyandconspicuouslydisclosethefactthat theyarecollectinglocationdata,thepurposeforthecollection, howlongthedataisretained,howthedataissecured,howthedata issharedifitisshared,howuserscanaccess,updateanddelete thedata,andanyotherchoicesthatusershavewithrespecttothe data.Thisdisclosureneedstoincludeanexplanationofany exceptionstotheguidelineslistedabove. 3.3 Implementationconsiderations Thissectionisnon-normative. Implementersareadvisedtoconsiderthefollowingaspectsthatcan negativelyaffecttheprivacyoftheirusers:incertaincases,users caninadvertentlygrantpermissiontotheuseragenttodisclose theirlocationtowebsites.Inothercases,thecontenthostedata certainURLchangesinsuchawaythatthepreviouslygranted locationpermissionsnolongerapplyasfarastheuserisconcerned. Ortheusersmightsimplychangetheirminds. Predictingorpreventingthesesituationsisinherentlydifficult. Mitigationandin-depthdefensivemeasuresareanimplementation responsibilityandnotprescribedbythisspecification.However,in designingthesemeasures,implementersareadvisedtoenableuser awarenessoflocationsharing,andtoprovideaccesstouser interfacesthatenablerevocationofpermissions. MDN🚫 Headers/Feature-Policy/geolocation Thisfeaturehaslimitedsupport. Chrome 60+ ChromeAndroid ? Edge ? EdgeMobile ? Firefox 74+ FirefoxAndroid ? Opera ? OperaAndroid ? Safari No SafariiOS ? SamsungInternet ? WebViewAndroid ? 3.4 CheckingpermissiontousetheAPI TheGeolocationAPIisadefaultpowerfulfeature identifiedbythename"geolocation". Whencheckingpermission tousetheAPI,auseragentMAYsuggesttime-basedpermission lifetimes,suchas"24hours","1week",orchooseto rememberthepermissiongrantindefinitely.However, itisRECOMMENDEDthatauseragentprioritizerestrictingthe permissionlifetimetoasinglesession:Thiscan be,forexample,untiltherealmis destroyed,theend-usernavigatesawayfromtheorigin,or therelevantbrowsertabisclosed. 4. Securityconsiderations TherearenosecurityconsiderationsassociatedwithGeolocationAPIat thetimeofpublication.However,readersareadvisedtoreadthe 3. Privacyconsiderations. MDN✅ Navigator/geolocation Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera 10.6+ OperaAndroid 11+ Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 5. ExtensionstotheNavigatorinterface WebIDLpartialinterfaceNavigator{ [SameObject]readonlyattributeGeolocationgeolocation; }; MDN✅ Geolocation Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid 4+ Opera 10.6+ OperaAndroid 11+ Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 6. Geolocationinterfaceandcallbacks WebIDL[Exposed=Window] interfaceGeolocation{ undefinedgetCurrentPosition( PositionCallbacksuccessCallback, optionalPositionErrorCallback?errorCallback=null, optionalPositionOptionsoptions={} ); longwatchPosition( PositionCallbacksuccessCallback, optionalPositionErrorCallback?errorCallback=null, optionalPositionOptionsoptions={} ); undefinedclearWatch(longwatchId); }; callbackPositionCallback=undefined( GeolocationPositionposition ); callbackPositionErrorCallback=undefined( GeolocationPositionErrorpositionError ); 6.1 Internalslots InstancesofGeolocationarecreatedwiththeinternalslotsin thefollowingtable: Internalslot Description [[cachedPosition]] AGeolocationPosition,initializedtonull.It'sareference tothelastacquiredpositionandservesasacache.Auseragent MAYevict[[cachedPosition]]byresettingitto nullatanytimeforanyreason. [[watchIDs]] Initializedasanemptylistofunsignedlong items. MDN✅ Geolocation/getCurrentPosition Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera 10.6+ OperaAndroid 11+ Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 6.2 getCurrentPosition()method ThegetCurrentPosition(successCallback, errorCallback,options) methodstepsare: Ifthecurrentsettingsobject'srelevantglobalobject's associatedDocumentisnotfullyactive: CallbackwitherrorerrorCallbackand POSITION_UNAVAILABLE. Terminatethisalgorithm. Inparallel,requestapositionpassing successCallback,errorCallback,andoptions. MDN✅ Geolocation/watchPosition Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera 10.6+ OperaAndroid 11+ Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 6.3 watchPosition()method ThewatchPosition(successCallback, errorCallback,options) methodstepsare: Ifthecurrentsettingsobject'srelevantglobalobject's associatedDocumentisnotfullyactive: CallbackwitherrorpassingerrorCallbackand POSITION_UNAVAILABLE. Return0. LetwatchIdbeanimplementation-defined unsignedlongthatisgreaterthanzero. AppendwatchIdtothis's [[watchIDs]]. Inparallel,requestapositionpassing successCallback,errorCallback,options,andwatchId. ReturnwatchId. MDN✅ Geolocation/clearWatch Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera 10.6+ OperaAndroid 11+ Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 6.4 clearWatch()method WhenclearWatch()isinvoked,theuseragentMUST: RemovewatchIdfromthis's [[watchIDs]]. 6.5 Requestaposition Torequestaposition,passaPositionCallback successCallback,aPositionErrorCallback? errorCallback,PositionOptions options,andanoptionalwatchId: LetwatchIDsbethis's[[watchIDs]]. Letdocumentbethecurrentsettingsobject's relevantglobalobject'sassociatedDocument. Ifdocumentisnotallowedtousethe "geolocation"feature: IfwatchIdwaspassed,removewatchIdfrom watchIDs. CallbackwitherrorpassingerrorCallbackand PERMISSION_DENIED. Terminatethisalgorithm. Ifdocument'svisibilitystateis "hidden",waitforthefollowingpagevisibilitychangestepsto run: Assert:document'svisibilitystateis "visible". Continuetothenextstepsbelow. LetdescriptorbeanewPermissionDescriptorwhose nameis"geolocation". Setpermissiontorequestpermissiontousedescriptor. Ifpermissionis"denied",then: IfwatchIdwaspassed,removewatchIdfrom watchIDs. CallbackwitherrorpassingerrorCallbackand PERMISSION_DENIED. Terminatethisalgorithm. WaittoacquireapositionpassingsuccessCallback, errorCallback,options,andwatchId. IfwatchIdwasnotpassed,terminatethisalgorithm. WhilewatchIDscontainswatchId: Waitforasignificantchangeof geographicposition.Whatconstitutesasignificant changeofgeographicpositionislefttotheimplementation. UseragentsMAYimposearatelimitonhowfrequentlyposition changesarereported. Ifdocumentisnotfullyactiveor visibilitystateisnot"visible",gobacktothe previousstepandagainwaitfora significantchangeofgeographicposition. Note:Positionupdatesareexclusivelyforfully-activevisibledocuments Thedesiredeffectherebeingthatpositionupdatesare exclusivelydeliveredtofullyactivedocumentsthatare visible;Otherwisetheupdatesgetsilently"droppedonthe floor".Onlyonceadocumentagainbecomesfullyactiveand visible(e.g.,aniframegetsreattachedtoaparent document),dothepositionupdatesonceagainstartgetting delivered. WaittoacquireapositionpassingsuccessCallback, errorCallback,options,andwatchId. 6.6 Acquireaposition Toacquireaposition, passingPositionCallbacksuccessCallback,a PositionErrorCallback?errorCallback, PositionOptionsoptions,andanoptional watchId. IfwatchIdwaspassedandthis's [[watchIDs]]doesnotcontainwatchId, terminatethisalgorithm. LetacquisitionTimebeanewEpochTimeStamp thatrepresentsnow. LettimeoutTimebethesumofacquisitionTimeand options.timeout. LetcachedPositionbethis's [[cachedPosition]]. Createanimplementation-specifictimeouttaskthatelapsesat timeoutTime,duringwhichittriestoacquirethedevice'sposition byrunningthefollowingsteps: Letpermissionbegetthecurrentpermissionstateof "geolocation". Ifpermissionis"denied": Stoptimeout. Dotheuserorsystemdenied permissionfailurecasestep. Ifpermissionis"granted": Letpositionbenull. IfcachedPositionisnotnull,and options.maximumAgeisgreaterthan0: LetcacheTimebeacquisitionTimeminusthe valueoftheoptions.maximumAge member. IfcachedPosition's timestamp'svalueisgreaterthan cacheTime,and cachedPosition.[[isHighAccuracy]] equalsoptions.enableHighAccuracy, setpositiontocachedPosition. Otherwise,ifpositionisnotcachedPosition,tryto acquirepositiondatafromtheunderlyingsystem,optionally takingintoconsiderationthevalueof options.enableHighAccuracyduring acquisition. Ifthetimeoutelapsesduringacquisition,oracquiring thedevice'spositionresultsinfailure: Stopthetimeout. Gotodealingwith failures. Terminatethisalgorithm. Ifacquiringthepositiondatafromthesystemsucceeds: SetpositionbeanewGeolocationPosition passingacquisitionTimeand options.enableHighAccuracy. Setthis's[[cachedPosition]]to position. Stopthetimeout. Queueataskonthegeolocationtasksourcewith astepthatinvokessuccessCallbackwithposition. Dealingwithfailures: Ifacquiringapositionfails,dooneofthefollowing basedontheconditionthatmatchesthefailure: Userorsystemdeniedpermission: CallbackwitherrorpassingerrorCallbackand PERMISSION_DENIED. Note:BrowserpermissionVSOSpermission Oncertainplatforms,therecanbeacircumstance wheretheuserhasgrantedtheuser agentpermissiontouseGeolocationatthe browser-level,butthepermissiontoaccess locationserviceshasbeendeniedattheOSlevel. Timeoutelapsed: CallbackwitherrorwitherrorCallbackand TIMEOUT. Dataacquisitionerrororanyotherreason: CallbackwitherrorpassingerrorCallbackand POSITION_UNAVAILABLE. 6.7 Callbackwitherror Wheninstructedtocallbackwitherror,givenan PositionErrorCallback?callbackandan unsignedshortcode: Ifcallbackisnull,return. Leterrorbeanewlycreated GeolocationPositionErrorinstancewhose codeattributeisinitializedtocode. Queueataskonthegeolocationtasksourcewithastep thatinvokescallbackwitherror. 7. PositionOptionsdictionary WebIDLdictionaryPositionOptions{ booleanenableHighAccuracy=false; [Clamp]unsignedlongtimeout=0xFFFFFFFF; [Clamp]unsignedlongmaximumAge=0; }; 7.1 enableHighAccuracymember TheenableHighAccuracymemberprovidesahintthatthe applicationwouldliketoreceivethemostaccuratelocationdata. Theintendedpurposeofthismemberistoallowapplicationsto informtheimplementationthattheydonotrequirehighaccuracy geolocationfixesand,therefore,theimplementationMAYavoidusing geolocationprovidersthatconsumeasignificantamountofpower (e.g.,GPS). Note:AwordofwarningaboutenableHighAccuracy TheenableHighAccuracymembercanresultinslowerresponsetimes orincreasedpowerconsumption.Theusermightalsodisablethis capability,orthedevicemightnotbeabletoprovidemore accurateresultsthaniftheflagwasn'tspecified. 7.2 timeoutmember Thetimeoutmemberdenotesthemaximumlengthoftime, expressedinmilliseconds,beforeacquiringapositionexpires. Note:Whenisthetimeoutcalculated? Thetimespentwaitingforthedocumenttobecomevisibleandfor obtainingpermissiontousetheAPIisnot includedintheperiodcoveredbythetimeout member.Thetimeoutmemberonlyapplieswhen acquiringapositionbegins. Note:Immediatecancellation Anoptions.timeoutvalue0cancause immediatefailures. 7.3 maximumAgemember ThemaximumAgememberindicatesthatthewebapplication iswillingtoacceptacachedpositionwhoseageisnogreaterthan thespecifiedtimeinmilliseconds. MDN✅ GeolocationPosition Thisfeatureisinallmajorengines. Chrome ? ChromeAndroid ? Edge No EdgeMobile ? Firefox ? FirefoxAndroid ? Opera 16+ OperaAndroid 16+ Safari ? SafariiOS ? SamsungInternet ? WebViewAndroid ? 8. GeolocationPositioninterface WebIDL[Exposed=Window,SecureContext] interfaceGeolocationPosition{ readonlyattributeGeolocationCoordinatescoords; readonlyattributeEpochTimeStamptimestamp; }; MDN✅ GeolocationPosition/coords Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera 16+ OperaAndroid 16+ Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 8.1 coordsattribute Thecoordsattributecontainsgeographiccoordinates. MDN✅ GeolocationPosition/timestamp Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera 16+ OperaAndroid 16+ Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 8.2 timestampattribute Thetimestampattributerepresentsthetimewhenthe geographicpositionofthedevicewasacquired. 8.3 Internalslots InstancesofGeolocationPositionErrorarecreatedwiththe internalslotsinthefollowingtable: Internalslot Description [[isHighAccuracy]] Abooleanthatrecordsthevalueofthe enableHighAccuracymemberwhenthis GeolocationPositioniscreated. 8.4 Tasksources Thefollowingtasksourceisdefinedbythisspecifications. Thegeolocationtasksource Usedbythisspecificationtoqueueupnon-blocking PositionCallbackandPositionErrorCallbackwhenperforming positionrequests. MDN✅ GeolocationCoordinates Thisfeatureisinallmajorengines. Chrome ? ChromeAndroid ? Edge No EdgeMobile ? Firefox ? FirefoxAndroid ? Opera ? OperaAndroid ? Safari ? SafariiOS ? SamsungInternet 1.0+ WebViewAndroid ? 9. GeolocationCoordinatesinterface WebIDL[Exposed=Window,SecureContext] interfaceGeolocationCoordinates{ readonlyattributedoubleaccuracy; readonlyattributedoublelatitude; readonlyattributedoublelongitude; readonlyattributedouble?altitude; readonlyattributedouble?altitudeAccuracy; readonlyattributedouble?heading; readonlyattributedouble?speed; }; MDN✅ GeolocationCoordinates/accuracy Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera ? OperaAndroid ? Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ MDN✅ GeolocationCoordinates/latitude Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera ? OperaAndroid ? Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ MDN✅ GeolocationCoordinates/longitude Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera ? OperaAndroid ? Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 9.1 latitude,longitude,andaccuracyattributes Thelatitudeandlongitudeattributesare geographiccoordinatesspecifiedindecimaldegrees. Theaccuracyattributedenotestheaccuracylevelofthe latitudeandlongitudecoordinatesinmeters(e.g.,65meters). MDN✅ GeolocationCoordinates/altitude Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera ? OperaAndroid ? Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ MDN✅ GeolocationCoordinates/altitudeAccuracy Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera ? OperaAndroid ? Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 9.2 altitudeandaltitudeAccuracyattributes Thealtitudeattributedenotestheheightoftheposition, specifiedinmetersabovethe[WGS84]ellipsoid. ThealtitudeAccuracyattributerepresentsthealtitude accuracyinmeters(e.g.,10meters). MDN✅ GeolocationCoordinates/heading Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera ? OperaAndroid ? Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 9.3 headingattribute Theheadingattributedenotesthedirectionoftravelof thehostingdeviceandisspecifiedindegrees,where0°≤heading <360°,countingclockwiserelativetothetruenorth. MDN✅ GeolocationCoordinates/speed Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera ? OperaAndroid ? Safari 5+ SafariiOS 3+ SamsungInternet ? WebViewAndroid 37+ 9.4 speedattribute Thespeedattributedenotesthemagnitudeofthe horizontalcomponentofthehostingdevice'scurrentvelocityin meterspersecond. 9.5 ConstructingaGeolocationPosition AnewGeolocationPositionisconstructedwith EpochTimeStamptimestampandboolean isHighAccuracybyperformingthefollowingsteps: Letcoordsbeanewlycreated GeolocationCoordinatesinstance: Initializecoord'slatitude attributetoageographiccoordinateindecimaldegrees. Initializecoord'slongitude attributetoageographiccoordinateindecimaldegrees. Initializecoord'saccuracy attributetoanon-negativerealnumber.ThevalueSHOULD correspondtoa95%confidencelevelwithrespecttothe longitudeandlatitudevalues. Initializecoord'saltitude attributeinmetersabovethe[WGS84]ellipsoid,ornullif theimplementationcannotprovidealtitudeinformation. Initializecoord's altitudeAccuracyattributeas non-negativerealnumber,ortonulliftheimplementation cannotprovidealtitudeinformation.Ifthealtitudeaccuracy informationisprovided,itSHOULDcorrespondtoa95%confidence level. Initializecoord'sspeed attributetoanon-negativerealnumber,orasnullifthe implementationcannotprovidespeedinformation. Initializecoord'sheading attributeindegrees,ornulliftheimplementationcannot provideheadinginformation.Ifthehostingdeviceisstationary (i.e.,thevalueofthespeed attributeis0),theninitializethe headingtoNaN. ReturnanewlycreatedGeolocationPositioninstancewithits coordsattributeinitializedtocoordsand timestampattributeinitializedto timestamp,andits[[isHighAccuracy]] internalslotsettoisHighAccuracy. MDN  GeolocationPositionError Chrome ? ChromeAndroid ? Edge No EdgeMobile ? Firefox ? FirefoxAndroid ? Opera 16+ OperaAndroid 16+ Safari 5+ SafariiOS ? SamsungInternet ? WebViewAndroid ? 10. GeolocationPositionErrorinterface WebIDL[Exposed=Window] interfaceGeolocationPositionError{ constunsignedshortPERMISSION_DENIED=1; constunsignedshortPOSITION_UNAVAILABLE=2; constunsignedshortTIMEOUT=3; readonlyattributeunsignedshortcode; readonlyattributeDOMStringmessage; }; 10.1 Constants PERMISSION_DENIED(numericvalue1) Requestapositionfailedbecausetheuserdeniedpermissionto usetheAPI. POSITION_UNAVAILABLE(numericvalue2) Acquireapositionfailed. TIMEOUT(numericvalue3) Thelengthoftimespecifiedbythetimeout memberhaselapsedbeforetheuseragentcouldsuccessfully acquireaposition. MDN✅ GeolocationPositionError/code Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera 16+ OperaAndroid 16+ Safari 5+ SafariiOS ? SamsungInternet ? WebViewAndroid 37+ 10.2 codeattribute Thecodeattributereturnsthevalueitwasinitializedto(see10.1 Constantsforpossible values). MDN✅ GeolocationPositionError/message Thisfeatureisinallmajorengines. Chrome 5+ ChromeAndroid ? Edge 12+ EdgeMobile ? Firefox 3.5+ FirefoxAndroid ? Opera 16+ OperaAndroid 16+ Safari 5+ SafariiOS ? SamsungInternet ? WebViewAndroid 37+ 10.3 messageattribute Themessageattributeisadeveloper-friendlytextual descriptionofthecodeattribute. Note:Don'tshow.messagetousers! ThepurposeofGeolocationPositionError's messageattributeistoassist developerswithdebugging.Forlegacyreasons,thisattributedoes notsupplylanguageorbasedirectionmetadataandisonly localizedintoEnglish.Developersareadvisedtouse GeolocationPositionError'scode attributetocreatealocalizedexperience. 11. Permissionspolicy TheGeolocationAPIdefinesapolicy-controlledfeatureidentifiedbythetokenstring"geolocation".Its defaultallowlistis'self'. 12.ConformanceAswellassectionsmarkedasnon-normative,allauthoringguidelines,diagrams,examples,andnotesinthisspecificationarenon-normative.Everythingelseinthisspecificationisnormative. ThekeywordsMAY,MUST,RECOMMENDED,andSHOULDinthisdocument aretobeinterpretedasdescribedin BCP14 [RFC2119][RFC8174] when,andonlywhen,theyappearinallcapitals,asshownhere. A.IDLIndex WebIDLpartialinterfaceNavigator{ [SameObject]readonlyattributeGeolocationgeolocation; }; [Exposed=Window] interfaceGeolocation{ undefinedgetCurrentPosition( PositionCallbacksuccessCallback, optionalPositionErrorCallback?errorCallback=null, optionalPositionOptionsoptions={} ); longwatchPosition( PositionCallbacksuccessCallback, optionalPositionErrorCallback?errorCallback=null, optionalPositionOptionsoptions={} ); undefinedclearWatch(longwatchId); }; callbackPositionCallback=undefined( GeolocationPositionposition ); callbackPositionErrorCallback=undefined( GeolocationPositionErrorpositionError ); dictionaryPositionOptions{ booleanenableHighAccuracy=false; [Clamp]unsignedlongtimeout=0xFFFFFFFF; [Clamp]unsignedlongmaximumAge=0; }; [Exposed=Window,SecureContext] interfaceGeolocationPosition{ readonlyattributeGeolocationCoordinatescoords; readonlyattributeEpochTimeStamptimestamp; }; [Exposed=Window,SecureContext] interfaceGeolocationCoordinates{ readonlyattributedoubleaccuracy; readonlyattributedoublelatitude; readonlyattributedoublelongitude; readonlyattributedouble?altitude; readonlyattributedouble?altitudeAccuracy; readonlyattributedouble?heading; readonlyattributedouble?speed; }; [Exposed=Window] interfaceGeolocationPositionError{ constunsignedshortPERMISSION_DENIED=1; constunsignedshortPOSITION_UNAVAILABLE=2; constunsignedshortTIMEOUT=3; readonlyattributeunsignedshortcode; readonlyattributeDOMStringmessage; }; B.IndexB.1Termsdefinedbythisspecification AnewGeolocationPosition §9.5 accuracyattributeforGeolocationCoordinates §9.1 acquireaposition §6.6 altitudeattributeforGeolocationCoordinates §9.2 altitudeAccuracyattributeforGeolocationCoordinates §9.2 [[cachedPosition]]internalslotforGeolocation §6.1 callbackwitherror §6.7 checkingpermission §3.4 clearWatch()methodforGeolocation §6.4 codeattributeforGeolocationPositionError §10.2 coordsattributeforGeolocationPosition §8.1 enableHighAccuracymemberforPositionOptions §7.1 geolocationattributeforNavigator §5. Geolocationinterface §6. geolocationtasksource §8.4 "geolocation" §3.4 GeolocationCoordinatesinterface §9. GeolocationPositioninterface §8. GeolocationPositionErrorinterface §10. getCurrentPositionmethodforGeolocation §6.2 headingattributeforGeolocationCoordinates §9.3 [[isHighAccuracy]]internalslotforGeolocationPosition §8.3 latitudeattributeforGeolocationCoordinates §9.1 longitudeattributeforGeolocationCoordinates §9.1 maximumAgememberforPositionOptions §7.3 messageattributeforGeolocationPositionError §10.3 PERMISSION_DENIED §10.1 POSITION_UNAVAILABLE §10.1 PositionCallback §6. PositionErrorCallback §6. PositionOptionsdictionary §7. requestaposition §6.5 speedattributeforGeolocationCoordinates §9.4 timeoutmemberforPositionOptions §7.2 TIMEOUT §10.1 timestampattributeforGeolocationPosition §8.2 [[watchIDs]]internalslotforGeolocation §6.1 watchPositionmethodforGeolocation §6.3 B.2Termsdefinedbyreference [PERMISSIONS]definesthefollowing: Permissions [PERMISSIONS-POLICY]definesthefollowing: PermissionsPolicy [WEBIDL]definesthefollowing: unsignedlongtype C. Acknowledgments Thissectionisnon-normative. Thisspecificationbuildsuponearlierworkintheindustry,including researchbyAzaRaskin,GoogleGearsGeolocationAPI,and LocationAware.org. ThanksalsotoAlecBerntson,AlissaCooper,SteveBlock,Greg Bolsinga,LarsErikBolstad,AaronBoodman,DaveBurke,ChrisButler, MaxFroumentin,ShyamHabarakada,MarcinHanclik,IanHickson,Brad Lassey,AngelMachin,CameronMcCormack,DanielPark,StuartParmenter, OlliPettay,ChrisPrince,ArunRanganathan,CarlReed,Thomas Roessler,DirkSegers,AllanThomson,MartinThomson,DougTurner,Erik Wilde,MattWomer,andMohamedZergaoui. D.ReferencesD.1Normativereferences [RFC2119] KeywordsforuseinRFCstoIndicateRequirementLevels.S.Bradner.IETF.March1997.BestCurrentPractice.URL:https://www.rfc-editor.org/rfc/rfc2119 [RFC8174] AmbiguityofUppercasevsLowercaseinRFC2119KeyWords.B.Leiba.IETF.May2017.BestCurrentPractice.URL:https://www.rfc-editor.org/rfc/rfc8174 [webidl] WebIDLStandard.EdgarChen;TimothyGu.WHATWG.LivingStandard.URL:https://webidl.spec.whatwg.org/ [WGS84] NationalImageryandMappingAgencyTechnicalReport8350.2,ThirdEdition.NationalImageryandMappingAgency.3January2000. D.2Informativereferences [Permissions] Permissions.MarcosCaceres;MikeTaylor.W3C.30July2022.W3CWorkingDraft.URL:https://www.w3.org/TR/permissions/ [Permissions-Policy] PermissionsPolicy.IanClelland.W3C.16July2020.W3CWorkingDraft.URL:https://www.w3.org/TR/permissions-policy-1/ ↑ Permalink Referencedin: §6.5Requestaposition §6.6Acquireaposition §11.Permissionspolicy Permalink Referencedin: §1.Introduction §3.1Userconsent §7.2timeoutmember Permalink exported Referencedin: Notreferencedinthisdocument. Permalink exported Referencedin: §5.ExtensionstotheNavigatorinterface §6.1Internalslots §A.IDLIndex Permalink exported Referencedin: §6.Geolocationinterfaceandcallbacks(2) §6.5Requestaposition §6.6Acquireaposition §8.4Tasksources §A.IDLIndex(2) Permalink exported Referencedin: §6.Geolocationinterfaceandcallbacks(2) §6.5Requestaposition §6.6Acquireaposition §6.7Callbackwitherror §8.4Tasksources §A.IDLIndex(2) Permalink Referencedin: §6.1Internalslots §6.6Acquireaposition(2) Permalink Referencedin: §6.3watchPosition()method §6.4clearWatch()method §6.5Requestaposition §6.6Acquireaposition Permalink exportedIDL Referencedin: §1.Introduction §2.4Handlingerrors §3.1Userconsent §6.Geolocationinterfaceandcallbacks §A.IDLIndex Permalink exportedIDL Referencedin: §1.Introduction §2.4Handlingerrors §3.1Userconsent §6.Geolocationinterfaceandcallbacks §A.IDLIndex Permalink exportedIDL Referencedin: §2.3Stopwatchingaposition §6.Geolocationinterfaceandcallbacks §A.IDLIndex Permalink Referencedin: §1.2Changelog §6.2getCurrentPosition()method §6.3watchPosition()method §8.4Tasksources §10.1Constants Permalink Referencedin: §1.Introduction §1.2Changelog §2.6Usingtimeout §6.5Requestaposition(2) §7.2timeoutmember(2) §10.1Constants(2) Permalink Referencedin: §6.2getCurrentPosition()method §6.3watchPosition()method §6.5Requestaposition(2) §6.6Acquireaposition(2)(3) §10.2codeattribute Permalink exportedIDL Referencedin: §1.Introduction §2.6Usingtimeout §6.Geolocationinterfaceandcallbacks(2) §6.5Requestaposition §6.6Acquireaposition §7.PositionOptionsdictionary §A.IDLIndex(2)(3) Permalink exportedIDL Referencedin: §1.Introduction §6.6Acquireaposition(2)(3) §7.PositionOptionsdictionary §8.3Internalslots §A.IDLIndex Permalink exportedIDL Referencedin: §2.6Usingtimeout §6.6Acquireaposition §7.PositionOptionsdictionary §7.2timeoutmember(2)(3) §10.1Constants §A.IDLIndex Permalink exportedIDL Referencedin: §1.Introduction §6.6Acquireaposition(2) §7.PositionOptionsdictionary §A.IDLIndex Permalink exported Referencedin: §1.Introduction §6.Geolocationinterfaceandcallbacks §6.1Internalslots §8.3Internalslots §9.5ConstructingaGeolocationPosition §A.IDLIndex Permalink exportedIDL Referencedin: §8.GeolocationPositioninterface §9.5ConstructingaGeolocationPosition §A.IDLIndex Permalink exportedIDL Referencedin: §6.6Acquireaposition §8.GeolocationPositioninterface §9.5ConstructingaGeolocationPosition §A.IDLIndex Permalink Referencedin: §6.6Acquireaposition §9.5ConstructingaGeolocationPosition Permalink Referencedin: §6.6Acquireaposition §6.7Callbackwitherror Permalink exportedIDL Referencedin: §8.GeolocationPositioninterface §9.GeolocationCoordinatesinterface §9.5ConstructingaGeolocationPosition §A.IDLIndex(2) Permalink exportedIDL Referencedin: §9.GeolocationCoordinatesinterface §9.5ConstructingaGeolocationPosition §A.IDLIndex Permalink exportedIDL Referencedin: §9.GeolocationCoordinatesinterface §9.5ConstructingaGeolocationPosition §A.IDLIndex Permalink exportedIDL Referencedin: §9.GeolocationCoordinatesinterface §9.5ConstructingaGeolocationPosition §A.IDLIndex Permalink exportedIDL Referencedin: §9.GeolocationCoordinatesinterface §9.5ConstructingaGeolocationPosition §A.IDLIndex Permalink exportedIDL Referencedin: §9.GeolocationCoordinatesinterface §9.5ConstructingaGeolocationPosition §A.IDLIndex Permalink exportedIDL Referencedin: §9.GeolocationCoordinatesinterface §9.5ConstructingaGeolocationPosition(2) §A.IDLIndex Permalink exportedIDL Referencedin: §9.GeolocationCoordinatesinterface §9.5ConstructingaGeolocationPosition(2) §A.IDLIndex Permalink Referencedin: §6.6Acquireaposition §8.3Internalslots Permalink exportedIDL Referencedin: §1.Introduction §2.4Handlingerrors §6.Geolocationinterfaceandcallbacks §6.7Callbackwitherror §8.3Internalslots §10.GeolocationPositionErrorinterface §10.3messageattribute(2) §A.IDLIndex(2) Permalink exportedIDL Referencedin: §6.5Requestaposition(2) §6.6Acquireaposition §10.GeolocationPositionErrorinterface §A.IDLIndex Permalink exportedIDL Referencedin: §6.2getCurrentPosition()method §6.3watchPosition()method §6.6Acquireaposition §10.GeolocationPositionErrorinterface §A.IDLIndex Permalink exportedIDL Referencedin: §6.6Acquireaposition §10.GeolocationPositionErrorinterface §A.IDLIndex Permalink exportedIDL Referencedin: §6.7Callbackwitherror §10.GeolocationPositionErrorinterface §10.3messageattribute(2) §A.IDLIndex Permalink exportedIDL Referencedin: §10.GeolocationPositionErrorinterface §10.3messageattribute §A.IDLIndex Permalink Referencedin: §1.2Changelog §D.2Informativereferences(2) Permalink Referencedin: §1.2Changelog §2.7EnablingtheAPIinthird-partycontexts §D.2Informativereferences(2) Permalink Referencedin: §6.1Internalslots §6.3watchPosition()method §6.7Callbackwitherror §D.1Normativereferences(2)



請為這篇文章評分?