JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
Web Geolocation API
Using the Geolocation API
The getCurrentPosition() method returns the user’s position.
The below example is used to return the latitude and longitude of the user’s position:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick=”getLocation()”>Try It</button>
<p id=”demo”></p>
<script>
const x = document.getElementById(“demo”);
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = “Geolocation is not supported by this browser.”;
}
}
function showPosition(position) {
x.innerHTML = “Latitude: ” + position.coords.latitude +
“<br>Longitude: ” + position.coords.longitude;
}
</script>
</body>
</html>
Output
JavaScript Geolocation API
Click the button to get your coordinates.
Example explained
- Check if Geolocation is supported.
- If supported, then run the getCurrentPosition() method. If not, show a message to the user
- If the getCurrentPosition() method is successful, it will return a coordinates object to the function specified in the parameter (showPosition)
- The showPosition() function outputs the Latitude and Longitude
Handling Errors and Rejections
The second parameter of the getCurrentPosition() method handles errors. It defines a function to run if it fails to get the user’s location:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick=”getLocation()”>Try It</button>
<p id=”demo”></p>
<script>
const x = document.getElementById(“demo”);
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = “Geolocation is not supported by this browser.”;
}
}
function showPosition(position) {
x.innerHTML = “Latitude: ” + position.coords.latitude +
“<br>Longitude: ” + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = “User denied the request for Geolocation.”
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = “Location information is unavailable.”
break;
case error.TIMEOUT:
x.innerHTML = “The request to get user location timed out.”
break;
case error.UNKNOWN_ERROR:
x.innerHTML = “An unknown error occurred.”
break;
}
}
</script>
</body>
</html>
Output
JavaScript Geolocation API
Click the button to get your coordinates.
Displaying the Result in a Map
To display the result in a map, access a map service, like Google Maps.
In the example below, the returned latitude and longitude are used to display the location in a Google Map (using a static image).
function showPosition(position) {
let latlon = position.coords.latitude + “,” + position.coords.longitude;
let img_url = “https://maps.googleapis.com/maps/api/staticmap?center=
“+latlon+”&zoom=14&size=400×300&sensor=false&key=YOUR_KEY”;
document.getElementById(“mapholder”).innerHTML = “<img src='”+img_url+”‘>”;
}
Location-specific Information
Geolocation is useful for location-specific information, like:
- Up-to-date local information.
- Displaying Points-of-interest near the user
- Turn-by-turn navigation (GPS)
The getCurrentPosition() Method – Return Data
The getCurrentPosition() method returns an object on success. The latitude, longitude, and accuracy properties are always returned. The other properties are returned if available.
Property | Returns |
coords.latitude | The latitude as a decimal number (always returned) |
coords.longitude | The longitude as a decimal number (always returned) |
coords.accuracy | The accuracy of position (always returned) |
coords.altitude | The altitude in meters above the mean sea level (returned if available) |
coords.altitudeAccuracy | The altitude accuracy of position (returned if available) |
coords.heading | The heading as degrees clockwise from North (returned if available) |
coords.speed | The speed in meters per second (returned if available) |
timestamp | The date/time of the response (returned if available) |
Geolocation Object – Other interesting Methods
The Geolocation object offers other interesting methods:
watchPosition() – Returns the current position of the user and continues to return the updated position as the user moves (like the GPS in a car).
clearWatch() – Stops the watchPosition() method.
The example below illustrates the watchPosition() method. You need an accurate GPS device to test this (like smartphone).
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick=”getLocation()”>Try It</button>
<p id=”demo”></p>
<script>
const x = document.getElementById(“demo”);
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = “Geolocation is not supported by this browser.”;
}
}
function showPosition(position) {
x.innerHTML=”Latitude: ” + position.coords.latitude +
“<br>Longitude: ” + position.coords.longitude;
}
</script>
</body>
</html>
Output
JavaScript Geolocation API
Click the button to get your coordinates.