FrontendWalla

Solutions for Real World Frontend Problems.

Finding your user’s location through HTML5 Geolocation.

Geolocation is an HTML5 interface that helps in identifying which part of the world you are
located in and sharing this information with people on your wish. The location is identified based on a number of ways like IP Address, WI-FI networks, Cellular Towers, or Specific GPS hardware in your Device.

Though sharing your location to the Web seems like a risky thing, you can share the information on your wish to trusted sites and always opt not to share if you don’t trust a site. There are many Websites that use this API to serve products and services near you.

One most popular and widely used sites are FourSquare which is a Social Networking Site where people can publish their location by check-in to the places of their interest. Each Check-in awards users some points and some of these points can actually be converted into goodies.

A similar App’s can be created using a combination of Geo-location API and some of the Map’s APIs to offer services like Stores, Hospitals, and Restaurants in users’ nearby locations.

Some of the Map’s API that can be used to find distances, places, driving directions etc are:
Google Maps API.
Microsoft’s Bing API.
OpenStreet Maps.
OVI Maps API by Nokia.

Lets quickly look at how to get Users location with the help of Geo-location.

All we will be writing is simple html and javascript to read the location of a User.

<!doctype html>
<html>
<head>
<title>My Geolocation App</title>
<script>
function getLocation(){
if(navigator.geolocation){
     navigator.geolocation.getCurrentPosition(showPosition,showError);
}else
{
     alert(“Geolocation API is not supported by your Browser”);
}
}

function showPosition(){
// implementation below
}

function showError(){
// implementation below
}
</script>
</head>
<body>
<script>getLocation();</script>
</body>
</html>



In the code above we have called a getLocation function which we have defined in the script.

The getLocation function first checks if navigator (Browser) supports the GeoLocation API
If it does not supports it alerts the same.

If browser supports the GeoLocation then we can call the method getCurrentPosition on the geolocation object. The Method takes two callback functions showPosition and showError.

showPosition is called when the coordinates are available.
And showError is called when there is some error in finding the location.


showPosition gets the position object, with the help of which we can get the latitude and longitude of users current position. This latitude and longitude information can be further converted into actual name of the place using what we call as reverse Geocoding.

function showPosition(position)
{
  lat =  position.coords.latitude;
  lng =  position.coords.longitude;
  alert(“You are located at Latitude: ” + lat + ” and Longitude ” + lng  );

}



showError gets the error object. Based on the error code. Different

function showError(error)
  {
  switch(error.code)
    {
    case error.PERMISSION_DENIED:
      alert(“User denied the request for Geolocation.”);
      break;
    case error.POSITION_UNAVAILABLE:
      alert(“Location information is unavailable.”);
      break;
    case error.TIMEOUT:
      alert(“The request to get user location timed out.”);
      break;
    case error.UNKNOWN_ERROR:
      alert(“An unknown error occurred.”);
      break;
    }
  }


Lets modify showPosition method to apply Reverse Geocoding to get the exact name of the place.
This can be done with the help of Maps API’s. We will use Google Map’s API for the same. To use google Map’s API will fist need to include the javascript api. Using the script tag in the head section.

<script type=”text/javascript” src=”http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false”></script>


Then we will modify the showPosition function.

function showPosition(position)
  {
  lat =  position.coords.latitude;
  lng =  position.coords.longitude;
  mylocation = new google.maps.LatLng(lat,lng);
 
   geocoder = new google.maps.Geocoder();
    geocoder.geocode({‘latLng’: mylocation}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {

myaddress = results[0].formatted_address;
alert(myaddress);
       
        }
      } else {
        alert(“Geocoder failed due to: ” + status);
      }
 });

 }


So using simple API’s we can find a user’s location and by combining it with Map’s API’s
extend this idea to create wonderful app’s to let user find particular services, products and places around him.




Finding your user’s location through HTML5 Geolocation.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top