HTML GEOLOCATION API


Share


The HTML Geolocation API is is used to to to locate a user's position. It is mainly used for local businesses, restaurants or showing location on the map. It uses JavaScript to give the latitude and longitude to the backend server. Most of the browsers supports Geo-location API. Geo-location API uses global navigator object which can be created as follows:


var loc = navigator.geolocation


Locate the user's position

The HTML geo location API is used to to Tu get the geographical position of a user.
Since this can compromise privacy the position is not available unless the user approves it


notes

geo location is most accurate for devices with GPS light smartphone

Now Let's look on Example:

Using HTML Geolocation :

The getCurrentPosition() method is used to return the user's position.

The upcoming example returns the latitude and longitude of the user's position.

Now Let's look on Example:


<!DOCTYPE html>

<html>

<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>

var 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>

example explained

  • check if geolocation is supported

  • if supported run the getCurrentPosition() Method if not display a a message to the user

  • if the GetCurrentPosition() method is successful it return a coordinates coordinates object to the function function the function function specified in the parameter (showPosition)

  • the showPosition() function outputs the the latitude and longitude


  • The example above is is very basic jio location script with no error handling


    Share Author Section