HTML5 Geolocation | Using geolocation in HTML5


The Geolocation API provides a method to locate the user’s exact  position. This is useful in a number of ways ranging from providing a user with location specific information to providing route navigation.Internet Explorer 9, Firefox, Chrome, Safari and Opera support Geolocation.

A number of different sources are used to attempt to obtain the user’s location, and each has their own varying degree of accuracy. A desktop browser is likely to use WiFi (accurate to 20m) or IP Geolocation which is only accurate to the city level and can provide false positives. Mobile devices tend to use triangulation techniques such as GPS (accurate to 10m and only works outside), WiFi and GSM/CDMA cell IDs (accurate to 1000m).

Use the getCurrentPosition() method to get the user's position.

The example below is a simple Geolocation example returning the latitude and longitude of the user's position:


<script>

var MyLoc=document.getElementById("demo");

function getUserLocation()

  {

  if (navigator.geolocation) //This will check if browser support geolocation.
   {
    navigator.geolocation.getCurrentPosition(showPosition);
   }
  else
  {
  MyLoc.innerHTML="Geolocation is not supported by this browser.";
  }
 
  }

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



The above function first Check if Geolocation is supported by browser If supported, run the getCurrentPosition() method. If Geolocation is supported by browser, display a message to the user .If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter ( showPosition ) and The showPosition() function gets the displays the Latitude and Longitude.

Displaying the Result in a Map

To display the result in a map, you need access to a map service that can use latitude and longitude, like Google Maps. Change the showPosition method like this .



<script>

var MyLoc=document.getElementById("demo");

function getUserLocation()

  {

  if (navigator.geolocation) //This will check if browser support geolocation.
   {
    navigator.geolocation.getCurrentPosition(showPosition);
   }
  else
  {
  MyLoc.innerHTML="Geolocation is not supported by this browser.";
  }
 
  }


function showPosition(position)

{

var latlon=position.coords.latitude+","+position.coords.longitude;

var img_url="http://maps.googleapis.com/maps/api/staticmap?center="

+latlon+"&zoom=14&size=400x300&sensor=false";

document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";

}

</script>




This script will display  location in map.
Tags: ,

Join Us!