Over a million developers have joined DZone.

GeoLocation API in HTML5

DZone 's Guide to

GeoLocation API in HTML5

· Web Dev Zone ·
Free Resource
HTML5 have cool feature that is provide gelocation of the user on the fly without using any extra services that we do right now. This feature is supported by Gelocation API which is part of HTML5.

Following is sample Code in JavaScript how it works.
<button onclick="getGeoLocation()">Get GeoLocation</button>
  function getGeoLocation()
    if (navigator.geolocation)
      alert("Geolocation is not supported by this browser.");
  function showPosition(position)
      alert("Latitude: " + position.coords.latitude + 
               "    Longitude: " + position.coords.longitude); 
Code is work in this pattern.
  1. First when user click on button it calls getGeoLocation
  2. In that function its first check navigator.geolocation supported or not.
  3. It calls Inbuilt JavaScript method getCurrentPosition which returns Postion object
  4. This Position object used by showPostion to display Latitude and Logitude 

Below is handleError function that used to handle any error which might occur while accessing GeoLocation of the user.
  function handleError(error)
     case error.PERMISSION_DENIED:
      alert("User denied the request for Geolocation.");
      alert("Location information is unavailable.");
     case error.TIMEOUT:
      alert("The request to get user location timed out.");
     case error.UNKNOWN_ERROR:
      alert("An unknown error occurred.");
Code of the function is self-explained by the values given.

Update GeoLocation as you Move with watchPosition
There is one of function which is part of Gelocation API that is very useful to get continues update of location as user moves from one place to another palce.
watchPosition - function that is used to achieve the above function.
To see how this works actually just replace getCurrentPosition function with watchPosition.
To stop updates from watchPosition you can use  clearWatch() of API.

Position Object
Both method returns Postion object as output. Following is list of property that is part of Position Object.

coords.latitude The latitude as a decimal number
coords.longitude The longitude as a decimal number
coords.accuracy The accuracy of position
coords.altitude The altitude in meters above the mean sea level
coords.altitudeAccuracy The altitude accuracy of position
coords.heading The heading as degrees clockwise from North
coords.speed The speed in meters per second
timestamp The date/time of the response

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}