Programming Tutorials

HTML5 Location - getCurrentPosition() in HTML5

By: Emiley J in HTML5 Tutorials on 2013-02-17  

You can create cool location based services using HTML5. Prior to HTML5 you would need a native application to do that. Imagine you want to create a navigation application that shows the current location of the user on a map (on the phone or on the web) and the dot moves as the user moves and you want to add other cool features such as showing restaurants nearby or showing routes from point a to b etc, you would need to develop a native application on the mobile phones to do this. HTML5 changes all that and you can do it all using simple JavaScript commands in the browser (on the phone or on the web).

HTML5 has the Geolocation API that comes with inbuilt functions and scripts such as getCurrentPosition() method to get the user's position. Most of the common browsers including IE9, Chrome, Firefox and Safari already support these APIs.

The below code demonstrates the use of getCurrentPosition() to get the location of the user and then display the location on a map using google maps api.

<script> 
  var x=document.getElementById("demo"); 
  function getLocation() 
    { 
    if (navigator.geolocation) 
      { 
      navigator.geolocation.getCurrentPosition(showPosition); 
      } 
    else{x.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>

The getCurrentPosition() Method

The getCurrentPosition() method returns an object if it is successful. The latitude, longitude and accuracy properties are always returned. The other properties below are returned if available.

Property Description
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





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in HTML5 )

Latest Articles (in HTML5)