home

Search A2Z 24

How To Detect The Location using JavaScript

X

Detecting the location of your website's users is useful for a variety of reasons. You might for instance want to display different content, perhaps in different languages for people from different countries, or display targeted information to visitors from different locations.

The Geolocation API

The geolocation API is a new html5 feature that allows a web page's visitor to share their location with you if they so choose. When you try to retrieve the location using this API, a prompt is shown to the user asking them if they will like to share their location with your site.

Example of the kind of prompt shown to the user

Obviously, this means that you won't get the location if the user decides not to share their location with you.

if ("geolocation" in navigator) {
  // check if geolocation is supported/enabled on current browser
  navigator.geolocation.getCurrentPosition(
     function success(position) {
        // for when getting location is a success
        console.log('latitude', position.coords.latitude,'longitude', position.coords.longitude);
     },
     function error(error_message) {
       // for when getting location results in an error
       console.error('An error has occured while retrieving location', error_message);
     }  
  );
} else {
  // geolocation is not supported
  // get your location some other way
  console.log('geolocation is not enabled on this browser');
}

Drawbacks: It only works on secure servers (https). It is not supported on Internet Explorer 10 and below and OperaMini.

The output from the code only gives us the coordinates.

Now that we have our location in one way or the other, we are going to convert the latitude and longitude we retrieved to a more comprehensive address using the Google Maps Reverse Geocoding API.

According to google, Reverse geocoding is the process of converting geographic coordinates into a human-readable address. All we need is an api key. Follow the steps to get one here

function getAddress (latitude, longitude) {
  $.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&key=' + GOOGLE_MAP_KEY)
  .then(
    function success (response) {
      console.log("User's Address Data is ", response);
    },
    function fail (status) {
      console.log('Request failed.  Returned status of',status);
    }
   )
}
getAddress(6.4531, 3.3958)

Here's what I got in my console.

Example output of the Reverse Geocoding API

You can play around with the object, to get the desired address in the format you like best.

Putting it all together, we have this.

function getAddress (latitude, longitude) {
  $.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&key=' + GOOGLE_MAP_KEY)
  .then(
    function success (response) {
      console.log("User's Address Data is ", response);
    },
    function fail (status) {
      console.log('Request failed.  Returned status of',status);
    }
   )
}
if ("geolocation" in navigator) {
  // check if geolocation is supported/enabled on current browser
  navigator.geolocation.getCurrentPosition(
    function success(position) {
        // for when getting location is a success
        console.log('latitude', position.coords.latitude,'longitude', position.coords.longitude);
        getAddress(position.coords.latitude, position.coords.longitude);
    },
    function error(error_message) {
       // for when getting location results in an error
       console.error('An error has occured while retrieving location', error_message);
    }
  );
} else {
  // geolocation is not supported
  // get your location some other way
  console.log('geolocation is not enabled on this browser');
}

About Author

by Admin

Reference Links

  1. w3schools html5 geolocation
loading...

Share your thoughts!

Login as a member to access comment posting block !! click-here

Thoughts From Other Users (0)

No Comments

×