HTML Geolocation API - W3Schools
文章推薦指數: 80 %
The HTML Geolocation API is used to get the geographical position of a user. ... Note: Geolocation is most accurate for devices with GPS, like smartphones. Tutorials References Exercises Videos Menu Login FreeWebsite GetCertified Pro HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP BOOTSTRAP HOWTO W3.CSS C C++ C# REACT R JQUERY DJANGO TYPESCRIPT NODEJS MYSQL Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnMongoDB LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises PythonExercises SQLExercises PHPExercises JavaExercises CExercises C++Exercises C#Exercises jQueryExercises React.jsExercises MySQLExercises Bootstrap5Exercises Bootstrap4Exercises Bootstrap3Exercises NumPyExercises PandasExercises SciPyExercises TypeScriptExercises ExcelExercises RExercises GitExercises KotlinExercises GoExercises MongoDBExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz PythonQuiz SQLQuiz PHPQuiz JavaQuiz CQuiz C++Quiz C#Quiz jQueryQuiz React.jsQuiz MySQLQuiz Bootstrap5Quiz Bootstrap4Quiz Bootstrap3Quiz NumPyQuiz PandasQuiz SciPyQuiz TypeScriptQuiz XMLQuiz RQuiz GitQuiz KotlinQuiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse PythonCourse SQLCourse PHPCourse JavaCourse C++Course C#Course jQueryCourse React.jsCourse Bootstrap4Course Bootstrap3Course NumPyCourse PandasCourse TypeScriptCourse XMLCourse RCourse DataAnalyticsCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate PythonCertificate SQLCertificate PHPCertificate JavaCertificate C++Certificate C#Certificate jQueryCertificate React.jsCertificate MySQLCertificate Bootstrap5Certificate Bootstrap4Certificate Bootstrap3Certificate TypeScriptCertificate XMLCertificate ExcelCertificate DataScienceCertificate CyberSecurityCertificate AccessibilityCertificate × Tutorials References Exercises GetCertified Spaces Videos Shop Pro HTMLTutorial HTMLHOME HTMLIntroduction HTMLEditors HTMLBasic HTMLElements HTMLAttributes HTMLHeadings HTMLParagraphs HTMLStyles HTMLFormatting HTMLQuotations HTMLComments HTMLColors Colors RGB HEX HSL HTMLCSS HTMLLinks Links LinkColors LinkBookmarks HTMLImages Images ImageMap BackgroundImages ThePictureElement HTMLFavicon HTMLTables HTMLTables TableBorders TableSizes TableHeaders Padding&Spacing Colspan&Rowspan TableStyling TableColgroup HTMLLists Lists UnorderedLists OrderedLists OtherLists HTMLBlock&Inline HTMLClasses HTMLId HTMLIframes HTMLJavaScript HTMLFilePaths HTMLHead HTMLLayout HTMLResponsive HTMLComputercode HTMLSemantics HTMLStyleGuide HTMLEntities HTMLSymbols HTMLEmojis HTMLCharset HTMLURLEncode HTMLvs.XHTML HTMLForms HTMLForms HTMLFormAttributes HTMLFormElements HTMLInputTypes HTMLInputAttributes HTMLInputFormAttributes HTMLGraphics HTMLCanvas HTMLSVG HTMLMedia HTMLMedia HTMLVideo HTMLAudio HTMLPlug-ins HTMLYouTube HTMLAPIs HTMLGeolocation HTMLDrag/Drop HTMLWebStorage HTMLWebWorkers HTMLSSE HTMLExamples HTMLExamples HTMLQuiz HTMLExercises HTMLCertificate HTMLSummary HTMLAccessibility HTMLReferences HTMLTagList HTMLAttributes HTMLGlobalAttributes HTMLBrowserSupport HTMLEvents HTMLColors HTMLCanvas HTMLAudio/Video HTMLDoctypes HTMLCharacterSets HTMLURLEncode HTMLLangCodes HTTPMessages HTTPMethods PXtoEMConverter KeyboardShortcuts HTMLGeolocationAPI ❮Previous Next❯ TheHTMLGeolocationAPIisusedtolocateauser'sposition. LocatetheUser'sPosition TheHTMLGeolocationAPIisusedtogetthegeographicalpositionofauser. Sincethiscancompromiseprivacy,thepositionisnotavailableunlesstheuserapprovesit. TryIt Note:GeolocationismostaccuratefordeviceswithGPS,likesmartphones. BrowserSupport Thenumbersinthetablespecifythefirstbrowserversionthatfullysupports Geolocation. API Geolocation 5.0-49.0(http)50.0(https) 9.0 3.5 5.0 16.0 Note:AsofChrome50,theGeolocationAPIwillonlyworkonsecurecontextssuch asHTTPS.Ifyoursiteishostedonannon-secureorigin(suchasHTTP)the requeststogettheuserslocationwillnolongerfunction. UsingHTMLGeolocation ThegetCurrentPosition()methodisusedtoreturntheuser'sposition. Theexamplebelowreturnsthelatitudeandlongitudeoftheuser'sposition: Example TryitYourself» Exampleexplained: CheckifGeolocationissupported Ifsupported,runthegetCurrentPosition()method.Ifnot,displayamessagetotheuser IfthegetCurrentPosition()methodissuccessful,itreturnsacoordinatesobjecttothefunctionspecifiedintheparameter(showPosition) TheshowPosition()functionoutputstheLatitudeandLongitude TheexampleaboveisaverybasicGeolocationscript,withnoerrorhandling. HandlingErrorsandRejections ThesecondparameterofthegetCurrentPosition()methodisusedtohandle errors.Itspecifiesafunctiontorunifitfailstogettheuser'slocation: Example functionshowError(error){ switch(error.code){ caseerror.PERMISSION_DENIED: x.innerHTML="UserdeniedtherequestforGeolocation." break; caseerror.POSITION_UNAVAILABLE: x.innerHTML="Locationinformationisunavailable." break; caseerror.TIMEOUT: x.innerHTML="Therequesttogetuserlocationtimedout." break; caseerror.UNKNOWN_ERROR: x.innerHTML="Anunknownerroroccurred." break; } } TryitYourself» Location-specificInformation Thispagehasdemonstratedhowtoshowauser'spositiononamap. Geolocationisalsoveryusefulforlocation-specificinformation,like: Up-to-datelocalinformation ShowingPoints-of-interestneartheuser Turn-by-turnnavigation(GPS) ThegetCurrentPosition()Method-ReturnData ThegetCurrentPosition()methodreturnsanobjectonsuccess.Thelatitude, longitudeandaccuracypropertiesarealwaysreturned.Theotherpropertiesarereturned ifavailable: Property Returns coords.latitude Thelatitudeasadecimalnumber(alwaysreturned) coords.longitude Thelongitudeasadecimalnumber(alwaysreturned) coords.accuracy Theaccuracyofposition(alwaysreturned) coords.altitude Thealtitudeinmetersabovethemeansealevel(returnedifavailable) coords.altitudeAccuracy Thealtitudeaccuracyofposition(returnedifavailable) coords.heading TheheadingasdegreesclockwisefromNorth(returnedifavailable) coords.speed Thespeedinmeterspersecond(returnedifavailable) timestamp Thedate/timeoftheresponse(returnedifavailable) GeolocationObject-OtherinterestingMethods TheGeolocationobjectalsohasotherinterestingmethods: watchPosition()-Returnsthecurrentpositionoftheuserandcontinuesto returnupdatedpositionastheusermoves(liketheGPSinacar). clearWatch()-StopsthewatchPosition()method. TheexamplebelowshowsthewatchPosition()method.YouneedanaccurateGPSdevicetotestthis(like smartphone): Example TryitYourself» ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame
延伸文章資訊
- 1What is a Geolocation API and how is it used? - PubNub
A Geolocation API is a communication interface between a client device or application (client-sid...
- 2[30apis] Day 2 : Google Map Geolocation API - iT 邦幫忙
關於Geolocation 在實作之前,我大致上知道Google Map 有個定位的API (廢話)但我一直以為它叫做location API。 所以在這邊對Location 跟Geolo...
- 3Overview | Geolocation API | Google Developers
The Geolocation API returns a location and accuracy radius based on information about cell towers...
- 4茶米老師教室- Geolocation API - Google Sites
HTML5 提供了Geolocation API 讓瀏覽者可以由網頁中或是設備的GPS 取得目前的位置。在網頁中您可以使用navigator.geolocation 來測試目前的瀏覽器是否支援G...
- 5HTML Geolocation API - W3Schools
The HTML Geolocation API is used to get the geographical position of a user. ... Note: Geolocatio...