Hey people,

Planning to update your application to a new level. Or thinking to add some new features to your current website. Well whatever you plan, do not forget to make it more intelligent. YES ! You can make your website more intelligent by making it enable to detect current location of the visitor visiting your website.

If your website is content related you can provide specific content related to visitor’s current location. That sounds little difficult at first but when you will see the real implementation you will come to know that how blessed day it is for you.

You can detect  visitor’s current location using a simple javascript function. This javascript function provides you the current latitudinal and longitudinal values of user’s location. These values are based on the hosting devices IP address. This technique may or may not be accurate but upto some level it is very helpful.


Geolocation on all browsers is becoming very common and popular. Today almost every browser is trying to implement geolocation. Even W3C has a standard for the geolocation now. The code to know the latitude and longitude is given below and a demo can be tested on this page.

<title> Know your current location </title>
<script type="text/javascript">
  navigator.geolocation.getCurrentPosition(getLocation, unknownLocation);
  function getLocation(pos)
    var latitde = pos.coords.latitude;
    var longitude = pos.coords.longitude;
    alert('Your current coordinates (latitide,longitude) are : ' + latitde + ', ' + longitude);
  function unknownLocation()
    alert('Could not find location');

The above function getCurrentPosition requires names of two arguments, which are function references. You can either write the name of the callback function or can also write inline anonymous functions to process the location information. On successful detection of location, the function getLocation is called to which object containing the location information is passed. You can store the values in variable and can do a Ajax call, display it on a map or whatever you like to utilize it with.

The second function,unknownLocation , is called just in case the location is not detected by any means. It can be a denial by the user or may be that the script is unable to detect the location. When the location of the user is shared, it first confirms from the user if he/she wants to share the location information or no. This is done at the browser’s end, as mentioned in the W3C API standards.

Currently the above script only alerts the location or failure, but you can utilize whatever the way you want to.

Hope you like this post and you learn something from this.

Stay Digified !!
Sachin Khosla

Share this post: