HTML5 Geolocation API using Google maps

By

December 18, 2012HTML5No comments

html5 geolocation apiHTML5 Geolocation api allows us to get the current location using a simple JavaScript function. On the modern browsers the location information can be retrieved using the Navigator object.

HTML5 Geolocation API

Navigator.geolocation()

This function simply queries the browser about the location from which the webpage is getting loaded.The browser which uses the location provider (in our case Google maps) to get the location information using the public IP address,MAC,Wifi information which is sent by the browser itself.

As accessing the physical location impacts user privacy the above function will not work when the user denies the permission for it.

html5 geolocation api-permissions

Geolocation is not supported only in modern browsers with HTML5 capabilities. To ensure this first we have to check the geolocation support.

1
2
3
4
5
6
7
8
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(onsuccess,onfailure);
}
Else
{
Console.log(“Geolocation is not supported by this browser.");
}

getCurrentPosition method uses the success and failure callbacks which we can use to get the latitude and longitude of the location.

1
2
3
4
5
Function onsuccess(position)
{
Var lat=position.coords.latitude;
Var lon=position.coords.longitude;
}

Browser will popup up for asking permission from the user when the user loads the page for the first time. When the permission was denied the onerror() method will be called.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function onfailure (error) {
if(error.code=1)
{
Alert(“Permission denied”);
}
Else if (error.code=2)
{
Alert(“Position Unavailable”);
}
Else
{
Alert(“Request timedout”);
}
}

Now we have the latitude and longitude of the user using HTML5 Geolocation API but we have to plot the coordinates on a map. For this purpose we can use Google maps javascript API to display a map with the coordinates.

Google Maps JavaScript API

Before we could access the API you have to login your google console and activate the Google Maps API v3 service.

google maps api

You need to generate a key to access the google services.

After activating you have to use the API key provided by google to use the maps on any webpage.

Google maps will display the full page maps of the current location once we provide the latitude and longitude.But the browser location may not be accurate since it relies only on the location information based on the ip address.

 

html5 geolocation api - maps preview

Complete Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
< !DOCTYPE html>
<html>
  <head>
    <title>HTML5 Geolocation API-Using Google maps</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
    <meta charset="utf-8"/>
    <style>
      html, body, #map_canvas {
       
        height: 100%;
       
      }
    </style>
   <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCh-y11IcabsG7Uy-y11IcabsG7UyWOZE&sensor=true">
    </script>
   
    <script>
      var map;
      function initialize() {
          
      if (navigator.geolocation)
        {
        navigator.geolocation.getCurrentPosition(showPosition);
        }
      else
        {
            x.innerHTML="Geolocation is not supported by this browser.";}
        }
      function showPosition(position)
      {
      var mapOptions = {
          zoom: 12,
          center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
            mapOptions);
           
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
            map: map,
            title: 'You are Here!'
        });
      }




      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html>

Download this code
Demo

 

Leave a Reply

*