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
延伸文章資訊
- 1HTML Geolocation API - W3Schools
The HTML Geolocation API is used to get the geographical position of a user. ... Note: Geolocatio...
- 2ipstack - Free IP Geolocation API
Locate website visitors for free using ipstack - a free, real-time IP address to location JSON AP...
- 3What 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...
- 4Geolocation API - W3C
The Geolocation API defines a high-level interface to location information associated only with t...
- 5HTML5 Geolocation API - BrowserLeaks
The Geolocation API gives websites access to a high-level interface that allows them to query phy...