The HTML Geolocation API is used to find a user’s position.

The Geolocation is one of the best HTML5 API which is used to identify the user’s geographic location for the web application.

This new feature of HTML5 allows you to explore the latitude and longitude directions of the current site’s visitor. These directions can be captured by JavaScript and send to the server which can show your present location on the site


In this tutorial, you will learn-

Locate the User’s Position

The HTML Geolocation API is used to get the geological situation of a user.

Since this can compromise privacy, the position isn’t accessible unless the user approves it.

Note: Geolocation is generally precise for gadgets with GPS, as cell phones.

Browser Support

Note: As of Chrome 50, the Geolocation API will just work on secure settings like HTTPS. On the off chance that your site is hosted on an non-secure origin (like HTTP) the requests to get the users location will at this point don’t work.


Using HTML Geolocation

The getCurrentPosition() technique is used to return the user’s position.

The example beneath returns the latitude and longitude of the user’s position:

Example

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

Click the button to get your coordinates.

Example explained:

• Check in case Geolocation is supported

• If supported, run the getCurrentPosition() technique. If not, show a message to the user

• If the getCurrentPosition() technique is successful, it returns a coordinates object to the function indicated in the parameter (showPosition)

• The showPosition() work outputs the Latitude and Longitude

The example above is an extremely fundamental Geolocation script, with no error handling.


Handling Errors and Rejections

The second parameter of the getCurrentPosition() strategy is used to handle errors. It determines a capacity to run in the event that it fails to get the user’s area:

Example

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;
  }
}

Displaying the Result in a Map

To display the outcome in a map, you need access to a map service, similar to Google Maps.

In the example underneath, the returned latitude and longitude is used to show the location in a Google Map (using a static picture):

Example

function showPosition(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 shown how to show a user’s situation on a map.

Geolocation is additionally very useful for location-specific data, as:

  • Up-to-date local information
  • Showing 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 exactness properties are constantly returned. Different properties are returned if accessible:

PropertyReturns
coords.latitudeThe latitude as a decimal number (always returned)
coords.longitudeThe longitude as a decimal number (always returned)
coords.accuracyThe accuracy of position (always returned)
coords.altitudeThe altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracyThe altitude accuracy of position (returned if available)
coords.headingThe heading as degrees clockwise from North (returned if available)
coords.speedThe speed in meters per second (returned if available)
timestampThe date/time of the response (returned if available)

Geolocation Object – Other interesting Methods

The Geolocation object likewise has other interesting methods:

• watchPosition() – Returns the current situation of the user and keeps on return updated situation as the user moves (like the GPS in a car).

• clearWatch() – Stops the watchPosition() method.

The example beneath shows the watchPosition() method. You need an accurate GPS gadget to test this (like cell phone):

Example

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

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your projects with us.


0 Comments

Leave a Reply

Avatar placeholder