HTML5 Geolocation is used to locate a user's position
The HTML5 Geolocation API is used to get the geographical position of a user.
Since this can compromise user privacy, the position is not available unless the user approves it.
Internet Explorer 9+, Firefox, Chrome, Safari and Opera support Geolocation.
Note: Geolocation is much more accurate for devices with GPS, like iPhone.
Use the getCurrentPosition() method to get the user's position.
The example below is a simple Geolocation example returning the latitude and longitude of the user's position:
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 the user's location:
To display the result in a map, you need access to a map service that can use latitude and longitude, like Google Maps:
In the example above we use the returned latitude and longitude data to show the location in a Google map (using a static image).
Google Map Script
How to use a script to show an interactive map with a marker, zoom and drag options.
This page demonstrated how to show a user's position on a map. However, Geolocation is also very useful for location-specific information.
The getCurrentPosition() method returns an object if it is successful. The latitude, longitude and accuracy properties are always returned. The other properties below are returned if available.
|coords.latitude||The latitude as a decimal number|
|coords.longitude||The longitude as a decimal number|
|coords.accuracy||The accuracy of position|
|coords.altitude||The altitude in meters above the mean sea level|
|coords.altitudeAccuracy||The altitude accuracy of position|
|coords.heading||The heading as degrees clockwise from North|
|coords.speed||The speed in meters per second|
|timestamp||The date/time of the response|
watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
clearWatch() - Stops the watchPosition() method.
The example below shows the watchPosition() method. You need an accurate GPS device to test this (like iPhone):
The perfect solution for professionals who need to balance work, family, and career building.
More than 10 000 certificates already issued!
The HTML Certificate documents your knowledge of HTML.
The HTML5 Certificate documents your knowledge of advanced HTML5.
The CSS Certificate documents your knowledge of advanced CSS.
The jQuery Certificate documents your knowledge of jQuery.
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The ASP Certificate documents your knowledge of ASP, SQL, and ADO.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
Your message has been sent to W3Schools.