This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
The Geolocation API is supported in all browsers:
Yes | Yes | Yes | Yes | Yes |
<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 + "
Longitude: " + position.coords.longitude; } </script>
The second parameter of the
method is used to handle errors. It specifies a function to run if it fails to get the user's location: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; } }
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=400x300&sensor=false&key=YOUR_KEY";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
The
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) |
<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>
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon