Code

Detecting Geo Location with Google API on HTML5

Test Browsers: Firefox 3.6.12, Google Chrome 8.0.552.215, Internet Explorer 9.0 beta, Safari 5.0.2
Result: Firefox, Chrome ,Safari : Pass IE9 : Fail
 
 This post is result of my experiments with Google APIs . I always used to be amazed with Google Maps. It powers many other maps based services like Google Maps website, Google Ride Finder, Google Transit etc. Its quick, versatile and  does not contain ads, but Google states in their terms and conditions that they reserve the right to display ads in the future.

Though all browsers asks for a permission from the user (popup for safari), like given below

 

Firefox PermissionHow it Works

If you allow, the browser gathers information about nearby wireless access points and your computer’s IP address. Then it sends this information to the default geolocation service provider, Google Location Services, to get an estimate of your location. That location estimate is then shared with the requesting website.

The code basically, lays down a google canvas on your site. The browser send your coordinates to the geolocation service provider, thus maps back to nearest location on the map. This screenshot below is my exact location at the time of writing this post .

Geo Location - Bangalore

Code

<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function success(position) {
 var s = document.querySelector('#status');
 if (s.className == 'success') {
 return;
 }

 s.innerHTML = "found you!";
 s.className = 'success';

 var mapcanvas = document.createElement('div');
 mapcanvas.id = 'mapcanvas';
 mapcanvas.style.height = '400px';
 mapcanvas.style.width = '560px';

 document.querySelector('article').appendChild(mapcanvas);

 var latlng = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
 var myOptions = {
 zoom: 15,
 center: latlng,
 mapTypeControl: false,
 navigationControlOptions:
{style: google.maps.NavigationControlStyle.SMALL},
 mapTypeId: google.maps.MapTypeId.ROADMAP
 };
 var map = new google.maps.Map(document.getElementById("mapcanvas"),
myOptions);

 var marker = new google.maps.Marker({
 position: latlng,
 map: map,
 title:"You are here!"
 });
}

function error(msg) {
 var s = document.querySelector('#status');
 s.innerHTML = typeof msg == 'string' ? msg : "failed";
 s.className = 'fail';

 // console.log(arguments);
}

if (navigator.geolocation) {
 navigator.geolocation.getCurrentPosition(success, error);
} else {
 error('not supported');
}

</script>

Problems?

  1. You are behind a Proxy Server.
  2. You are behind a VPN.
  3. Simply a slow Internet. Try refreshing the page.
 Though my Chrome kept showing me older cached location. Even after clearing entire history. It even works good for Wireless Datacards.
Tagged , , ,