HTML5 geolocation (geolocation) is used to locate the user's location.
Locate the user's location
HTML5 geolocation API to get the user's geographic location
The user's location information is not available unless the user consents to the privacy of the user, given that this feature may be low.
HTML5-Using geo-positioning
Please use the Getcurrentpositon () method to get the user's location
The following example is a simple geo-location instance that returns the latitude and longitude of a user's location
Directly on the code bar:
<script>var x=document.getelementbyid ("demo"); function getLocation () { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition ( showposition); } Else {x.innerhtml= "The browser does not support obtaining a geographic location. ";} } function showposition (position) { x.innerhtml= "Latitude:" + position.coords.latitude + "<br>longitude:" + position.coords.longitude; } </script>
Instance parsing:
Detect whether geo-targeting is supported
If supported, run the GetCurrentPosition () method. If not supported, several users display a message.
If Getcuurentposition () runs successfully, returns a coordinates object to the function specified in the parameter showposition
The Showpostion () function gets and displays the longitude and latitude
Handling Errors and rejections
The second parameter of the GetCurrentPosition () method is used to handle the error, which specifies the function that runs when the user location fails:
functionShowError (Error) {Switch(error.code) { Caseerror. Permission_denied:x.innerhtml= "The user denied a request to obtain a geographic location." " Break; Caseerror. Position_unavailable:x.innerhtml= "Location information is not available." " Break; Caseerror. Timeout:x.innerhtml= "Request User location timeout." " Break; Caseerror. Unknown_error:x.innerhtml= "Unknown error. " Break; } }
Geolocation objects-Other interesting methods
Catchposition ()-Returns the user's current location and continues to return to the updated location when the user moves (just like the car's GPS)
Clearwatch ()-Stop watchposition () method
The following example shows the Watchposition () method, you need a precise GPS setting to test the example
<script>var x=document.getelementbyid ("demo"); function getLocation () { if (navigator.geolocation) { navigator.geolocation.watchPosition (showposition); } Else {x.innerhtml= "The browser does not support obtaining a geographic location. ";} } function showposition (position) { x.innerhtml= "Latitude:" + position.coords.latitude + "<br> Longitude:" + position.coords.longitude;< c21/>}</script>
The end of this section
HTML5 Study notes geolocation (geo-location)