Geolocation in HTML – getCurrentPosition()
What is Geolocation?
Geolocation is used to retrieve the geographical location of a user
Example of Geolocation:
The most basic usage of geolocation is implemented in Maps, using GPS – Gets the current user location and show the route to reach the destination
Geolocation Methods:
There are 2 methods provided by geolocation to determine user’s location,
- getCurrentPosition()
- watchPosition()
getCurrentPosition():
This method is used to retrieve the current geographical location of a user.
Syntax:
getCurrentPosition(callbackFunction, ErrorHandler, Options)
callbackFunction – Function to retrieve current location
ErrorHandler – Function called when error occurs
Options – Optional parameters to set options
The getCurrentPosition() method calls callbackFunction, which takes the position as an Object argument. The position object returns 2 properties – coords and timestamp
The coords property has various attributes,
coords.latitude – specifies latitude
coords.longitude – specifies longitude
coords.accuracy – accuracy of position
coords.altitude – altitude level
coords.altitudeAccuracy – accuracy of altitude
Example:
<html> <head> <title>Geo Location</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p id="button">Click here for location</p> <Button onclick="getLocation()">Locate</Button> <script> var geo=document.getElementById("button"); function getLocation() { if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(getPosition); } else { geo.innerHTML="Geolocation Not Supported"; } } function getPosition(position) { geo.innerHTML="Latitude: "+position.coords.latitude+ "<br> Longitude: "+position.coords.longitude; } </script> </body> </html>