In this article, we will know HTML Geolocation, various properties, methods & their implementation through examples.
var loc = navigator.geolocation
Location Properties: The following table determines properties used in getCurrentPosition() and their returning values.
- coords.latitude: Always returns latitude as a decimal number.
- coords.accuracy: Always returns the accuracy of position.
- coords.longitude: Always returns longitude as a decimal number.
- coords.altitude: Returns the altitude in meters above sea level if available.
- coords.altitudeAccuracy: Returns altitude accuracy of position if available.
- coords.heading: Returns heading in degree clockwise from North if available
- coords.speed: Returns speed in mps, if available.
- timestamp: Returns date or time of response if available
Geolocation Methods: The Geolocation has following methods which make it interesting and easier to work.
- getCurrentPosition(): It fetches the current location of the user.
- watchPosition(): It fetches periodic updates of the user’s current location.
- clearWatch(): It cancels a watchPosition call currently in execution.
Example: This example explains returning the user’s current location using the getCurrentPosition() method.
The above function can also be written without creating a navigator object as shown below:
Example: In this example, we simply display the current location with the help of latitude and longitude via HTML Geolocation.
Error and Rejection Handling: It is very important to handle the errors generated in Geolocation and show a required message when an error occurs. Functions like getCurrentPosition() make use of an error handler to handle the error generated (function errHand as used in the above example). The PositionError object used by the error handler has two properties that let the function handle error efficiently.
Generated errors in geolocation:
|UNKNOWN_ERRROR||An unknown error|
|PERMISSION_DENIED||The application doesn’t have permission to make use of location services|
|POSITION_UNAVAILABLE||The location of the device is uncertain|
|TIMEOUT||The time to fetch location information exceeded the maximum timeout interval|
Example: This example shows the above-approach.
Displaying result in MAP: Displaying location on a map is a very interesting task. These services are used to provide the exact location on the map.
Example: This example describes getting the current position in Google Maps with the help of latitude and longitude via HTML Geolocation.
- Google Chrome 5 and above
- Microsoft Edge 12 and above
- Firefox 3.5 and above
- Internet Explorer 9 and above
- Opera 10.6 and above
- Safari 5 and above
Please Login to comment...