How To Use HTML5 Geolocation With JavaScript

Posted By : Vivek Uniyal | 14-Apr-2020

The HTML Geolocation API is used to locate the user's current position. Let's explore how to use HTML5 Geolocation with JavaScript.

 

Locate the User's Position

The HTML Geolocation API is used to get the geographical current position of a user in SaaS application development. Since this can compromise privacy, the current position is not available unless the user approves it.

 

How to use HTML Geolocation

The getCurrentPosition() method is used to return the user's current position.
The example below will returns the latitude and longitude of the user's  current position:

<script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(show_Position);
  } else {
   x.innerHTML = "Geolocation not supported by browser.";
  }
}

function show_Position(position) {
 x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

 

Example explained:

Check if Geolocation is supported
If supported, run this getCurrentPosition() method. If not, display a message to the user
If this getCurrentPosition() method is executed successful then it will returns the current coordinates object to the function specified in the parameter (show_Position)
The show_Position() function outputs the Latitude and Longitude


Displaying The Result In a Map

To display the result in a map, you need access map service, like Google Maps.
In the example below, the returned latitude and longitude are used to show the location in a Google Map (using a static image):

function show_Position(position) {
  var latlon = position.coords.latitude + "," + position.coords.longitude;

  var 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+"'>";
}


Location-specific Information

This page has demonstrated how to show a user's current position on a map.
Geolocation is also very useful for current location-specific information, like:
Up-to-date local information
Showing Points-of-interest near the user
Turn-by-turn navigation (GPS)

 

Geolocation Object - Other interesting Methods

The Geolocation object also has other interesting methods:
watchPosition() - Returns the current position of the user and continues to return updated current position as the user moves (like the GPS in a car).
clearWatch() - Stops the watchPosition() method.

 

So this how we can see the user's current location and can use it to perform other operation.
 

About Author

Author Image
Vivek Uniyal

Vivek is a Front-end developer and has knowledge of Angular, HTML 5, CSS 3, Bootstrap, and JavaScript. he also has working knowledge of Back-end as well.

Request for Proposal

Name is required

Comment is required

Sending message..