Translate

Sunday, August 26, 2012

How to detect user location using Google Maps, Geolocation API and HTML5

Source: http://yourravi.com/detect-user-location-using-google-maps-geolocation-api-html5/




Seen Google Maps? Amazing isn’t it? Wanna use it to track your friend’s or girlfriend’s location. If yes, then just sit back and read our monthly superpost wherein we’ll explain how Google Maps can be used in conjunction with Geolocation API and HTML 5 to detect anyone’s location on Map.
Not only this, you can also track if the subject is changing location – whether he/she is moving and where he/she is heading.
In the tutorial, we’ll do simple stuff – just mark user location and show it on map. Here is the demo of what we’re building. [Click 'Allow' when asked for permission]
For easy grasp, we’ll break the code in pieces and discuss every bit in detail.
Let’s start,

First, some Terminology

1. Geolocation API: The API provides additional properties to navigator object that helps in detecting user’s (browser, in fact) latitude and longitude positions. These values are detected and transferred to Google Maps as parameter, which shows the location accordingly on map. All modern browsers those support HTML5 – IE9+, Firefox 3.5+, Safari5+, Chrome5+, Opera10.6+, iPhone3+, Android2+ support Geolocation API. [More on Geolocation API]
2. Google Maps API: This API define functions for easy interaction with Google Maps. API functions take coordinate values (latitude and longitude) of user location and shows it on map as output. [More on Google Maps API]
3. HTML5: It’s as advanced version of HTML with added features. All modern browsers supporting HTML 5 provides inbuilt support to Geolocation API as well. [More on HTML5]

How Maps would appear in output

In the HTML code, we do the following things,
  1. Specify <!DOCTYPE html> according to HTML5 standards,
  2. Load Google Maps JavaScript API <script src="http://maps.google.com/maps/api/js?sensor=false"></script> to use its functions for interaction with Google Maps.
  3. Define two divs – #location_div where location name would show up (like Delhi, India), and #map_div is where the output map would appear.
  4. Height and width of all elements is set to 100% as we want to show the map over the entire webpage.
Program execution starts when the JavaScript function location_info() is called on onLoad() event in the <body></body> tag. Here is the code,
<!DOCTYPE html style='width:100%;height:100%;'>

<head>
 <title>Tracking location using Google Maps API, Geolocation API in HTML5 supporting browsers
 </title>

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>

<body onload='location_info()'>
 <div id='location_div' style='background:black;'></div>
 <div id='map_div' style='width:100%;height:100%;'></div>
</body>
Next is the big JavaScript code that does all the work. Here we first get the coordinates of user, then send them to Google Maps and display the returned Map with user location marked on it.

Get coordinates, send to Google Maps API and show location on Map

1. location_info function is called on page load JS event. This function calls the getCurrentPostion() method of Geolocation API, which must have 2 callback functions – one that’ll be called when program runs normally (get_coords) and other one when there is an error in execution (if_error).
function location_info()
{
 navigator.geolocation.getCurrentPosition(get_coords, if_error);
}
Additional Info: Besides, there are 3 optional arguments – enableHighAccuracy, timeout and maximumAge.
  1. enableHighAccuracy is a Boolean argument with true/false value. By default, its false. When its turned true, results are more accurate but there could be delay in fetching result.
  2. timeout is the maximum time program can wait for results to appear. It’s counted after user consents to detect his location.
  3. maximumAge is time for which a location information for user should remain in browser cache. Suppose, maximumAge is set to 12000 ie 2 minutes then location retrieved at 10:00am till 10:02am would be the same. It’ll alter after the maximumAge is elapsed.
Here is how the function would appear with both callback functions and optional arguments.
function location_info()
{
 navigator.geolocation.getCurrentPosition(get_coords, if_error, {enableHighAccuracy:true, timeout:10000, maximumAge:75000});
}
2. In the next function, we collect the longitude and latitude coordinates for a user and send to google.maps.LatLng() function as parameter.
We also define zoom level, type of map in mapsOptions array. This array is then passed to google.maps.Map() function that creates an object of Map class.
An object of Marker class – marker is created to mark the location in red colored sticker.
reverse_geocode() function is called at the end that returns address name to users longitude and latitude coordinate.
function get_coords(position)
{
 var latitude=position.coords.latitude;
 var longitude=position.coords.longitude;

var mapsOptions={
 zoom: 12,
 center: new google.maps.LatLng(latitude, longitude),
 mapTypeId: google.maps.MapTypeId.ROADMAP
 }

var map=new google.maps.Map(document.getElementById("map_div"), mapsOptions);

var marker = new google.maps.Marker({
 position: pos,
 map: map,
 title: "User location"
 });

reverse_geocode();
}
3. Location name for user coordinates
Using geocode() method of Geocoder class, we can map the near-exact address for a pair of longitude and latitude coordinates. Here, we already have the coordinates and hence we can get the location as well.
Look at the following code that displays address inside the #location_div,
function reverse_geocode()
{
 geocoder.geocode({'latLng': pos}, function(results, status){
 if (status == google.maps.GeocoderStatus.OK)
 {
 if (results[1])
 {
 document.getElementById('location_div').innerHTML="<p style='margin:0px;padding:5px;color:white;font-weight:bold;font-size:12px;color:#ededed;font-family:Tahoma;'> Now you're at <span
 style='color:white;'>"+results[1].formatted_address+"</span></p>";
 }
 }
 else
 {
 alert("Geocoder failed due to: " + status);
 }
 });
}

Error handling

There may occur some problems while detecting user’s geolocation. In such cases, the second callback function if_error() is called instead of get_coords().
Below are the error values that might pop-in,
  • 1 is returned when user denies geolocation tracking.
  • 2 is when the google maps doesn’t return geolocation value either because coordinates are wrong or an app exhausted the given number of free requests, or any other reason.
  • 3 is when the app/program is kept waiting for time longer than what specified in the getCurrentPosition() function.
function if_error(err)
{
 if(err.code==1){alert('User Denied');}
 if(err.code==2){alert('Position unavailable');}
 if(err.code==3){alert('Timeout');}
}
On executing the code, this is how it’ll run. First user would see a opt-in in browser that’ll ask for user consent.
permission for detecting user location using geolocation API in chrome browser
If user allows, coordinates are sent to Google maps and result is retrieved and shown. If user denies, error 1 pops-in an alert with message ‘User Denied’.
The location sharing system is highly secure and programs can only read location if user grants permission. The entire system is fool-proof and location can’t be read by any other means.
(Post under updation…)

Let your friends find this article, just share it!