1-2-25
The HTML Geolocation API is used to locate a user's position.
The HTML Geolocation API used to get the geographical position of a user.
Note: geolocation is most accurate for devices with GPS, like smartphones.
Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure orgin (such as HTTP) the requests to get the users location will no longer function.
The getCurrentPosition() method is used to return the user's position.
The example below returns the latitude and longitude of the user's position:
Click the button to get your coordinates.
Example explained:
The example above is a very basic Geolocation script, with no error handling
The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get to get the user's location:
Click the buuton to get your coordinates.
This page has demonstrated how to show a user's position on a map.
Geolocation is also very useful for location-specific information, like:
The getCurrentPosition() method returns an object onsuccess. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:
Property |
---|
coords.latitude |
coords.longitude |
coods.accuracy |
coods.altitude |
coods.altitudeAccuracy |
coods.heading |
coods.speed |
timestamp |
The Geolocation object also has other interesting methods:
The example below shows the watchPosition() method. You need an accurate GPS device to test this (like smartphone):
Click the button to get your coordinates.