Track Current Location using HTML5 Geolocation and Google Maps API

Geolocation is one the best and most used HTML5 APIs, so lets see what we can do with it. Geolocation allows you to determine your current physical coordinates through your Web Browser. In this article I will show you how to use HTML5 Geolocation API to get your current position and hook the position into Google Maps API, to show the current position.The Google Maps API let you integrate Google Maps services in your Website.

View Demo

HTML5 Geolocation

Using JavaScript we can gather our current position.Please keep in mind that some ISPs are little quirky with Geolocation,sometimes they show you in a different area rather than you actually are.But hey, 99% of the time it’s fine.And kindly don’t blame me or the script, It’s Internet/ISP fault.

First of all, We’ll check that does our Browser Support HTML5 Geolocation API or not and for that We will be using the geolocation object, which allow us to gather Geographic location from the device.This looks like:

navigator.geolocation

Detecting HTML5 Geolocation API Browser Support

Now We’ll be detecting the HTML5 Geolocation API and it looks like:

if(navigator.geolocation){
  //Support
  console.log("Geolocation is Supported");
}else{
  //No Support
  console.log("Geolocation is not Supported for this browser/OS.");
}

We are using If Statement in the above code to detect HTML5 Geolocation API. The else statement is used for the fallbacks. If the Browser doesn’t support the HTML5 Geolocation API we will simply alert the user that your browser doesn’t support the API as we are not building anything for production environment.

Browsers Support

BrowserVersion
5.0+
9.0+
3.5+
16.0+
5.0+

Detecting Current Position

Now If our browser supports the HTML5 Geolocation API, We’ll try to gather our current location.

Note: HTML5 Geolocation API can compromises user privacy, the position is not available unless the user approves it.

Here, how we would gather our current physical coordinates using JavaScript’s getCurrentPosition() function and attaching it to geolocation object.

var position = navigator.geolocation.getCurrentPosition();

And then we will hook this up to with our Latitude and longitude.

var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

Now as we have the Physical Coordinates of our user, we will plot it on Google Map using the Google Map API v3.

[moptin id="3100"]

Google Maps API v3

Using the Google Map API, we can create a Google Map and Plot the current location on map.

Obtaining the Google Maps API key

To work with Google Map JavaScript API you need to create or select a project in the Google Developers Console and enable the API. Click this link, which guides you through the process and automatically Activates the Google Maps API.

Alternatively, you can manually activate the Google Maps API from Google Developers Console.

  1. Go to Google Developers Console
  2. Select a Project, or Create a new one
  3. Create new Client ID from the Left Sidebar>>Credentials
  4. Copy your API KEY
Note: For complete guide on How to get API key from Google Developers Console, read this article.

Now After getting your API Key add the below code to your Page.Here’s the code:

<script src="https://maps.googleapis.com/maps/api/js?key=API-KEY"></script>

Replace the API-KEY to your Google API key which you have copied from the Google Developers Console.

Now we will plot the position coordinates on simple Google maps.And here it is what the code will be look like:


window.onload = function(){
  var container = document.getElementById('map-canvas');
  if(navigator.geolocation){
    
    navigator.geolocation.getCurrentPosition(function(position){
        
        var latitude = position.coords.latitude,
            longitude = position.coords.longitude;
        var map,
            mapOptions = {
               zoom: 15,
               center: {lat: latitude,lng: longitude},
               mapTypeId: google.maps.MapTypeId.ROADMAP
            };
        map = new google.maps.Map(container,mapOptions);
        
        var geolocate = new google.maps.LatLng(latitude,longitude);
        
        var infowindow  = new google.maps.InfoWindow({
            map: map,
            position: geolocate,
            content: 
                    '<h1>Your Current Location is:</h1>'+
                    '<h2>Latitude: '+latitude+'</h2>'+
                    '<h2>Longitude: '+longitude+'</h2>'
        });
    },handleError);
    
    function handleError(error){
      //Handle Errors
    }
  }else{
      container.innerHTML = "Geolocation is not Supported for this browser/OS.";
  }
};

You’ll see I have included some <h1> and <h2> tags in the above which will show the Information to the user.Here how it’s look like:

Google Maps InfoWindow

HTML Code

Your HTML Code will look like:

<!DOCTYPE html>
<html>
<head>

<title>Tracking Current Location with HTML5 Geolocation and Google Maps API</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API-KEY"></script>

</head>
<body>

<div id="map-canvas" style="height:100%;width:100%"></div>

<script>
//JavaScript Code goes here...
</script>
</body>
</html>

Handling Errors and Rejections

The second parameter of getCurrentPosition() method is used to handle Errors and Rejections.It specifies a function if it fails to get the Users current position.

    function handleError(error){
        switch(error.code) {
            case error.PERMISSION_DENIED:
                container.innerHTML = "User denied the request for Geolocation."
                break;
            case error.POSITION_UNAVAILABLE:
                container.innerHTML = "Location information is unavailable."
                break;
            case error.TIMEOUT:
                container.innerHTML = "The request to get user location timed out."
                break;
            case error.UNKNOWN_ERROR:
                container.innerHTML = "An unknown error occurred."
                break;
        }
    }

The getCurrentPosition() Method – Return Data

The getCurrentPosition() method returns an object if it’s successful.The latitude,longitude and accuracy properties are always returned.It also return some other properties if available.

PropertyDescription
coords.latitudeThe latitude as a decimal number
coords.longitudeThe longitude as a decimal number
coords.accuracyThe accuracy of tracked position
coords.altitudeThe altitude in meters above the mean sea level
coords.altitudeAccuracyThe altitude accuracy of tracked position
coords.headingThe heading as degrees clockwise from North
coords.speedThe speed in meters per second
timestampThe date/time of the response

It’s look like:
getCurrentPosition Return Data

Periodic Update of Geolocation

If you wants that the coordinates automatically gets updated to it’s new coordinates, then you should use watchPosition() method.

watchPosition() – Returns the current position of the user and continues to return updated position as user moves (like a GPS).

clearWatch() – Stop the watchPosition() method.

The Example below show the watchPosition() and clearWatch() Method.

<!DOCTYPE html>
<html>
<head>

<title>Tracking Current Location with HTML5 Geolocation and Google Maps API</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API-KEY"></script>

</head>
<body>

<div id="map-canvas" style="height:100%;width:100%"></div>

<div>
<input type="button" onclick="trackPosition()" value="Track Me"/>
<input type="button" onclick="clearTracking()" value="Clear"/>
</div>

<script type="text/javascript">
var watchID;
function trackPosition(){
  if(navigator.geolocation){
    watchID =  navigator.geolocation.watchPosition(drawGoogleMap,handleError,{enableHighAccuracy: true});
  }else{
      document.getElementById('map-canvas').innerHTML = "Geolocation is not Supported for this browser/OS.";
  }
}

function clearTracking(){
    if(watchID>0){
        navigator.geolocation.clearWatch(watchID);
    }
}
    
function drawGoogleMap(position){
    var container = document.getElementById('map-canvas');
        
    var latitude = position.coords.latitude,
        longitude = position.coords.longitude;
    var map,
        mapOptions = {
        zoom: 15,
            center: {lat: latitude,lng: longitude},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    map = new google.maps.Map(container,mapOptions);
        
    var geolocate = new google.maps.LatLng(latitude,longitude);
        
    var infowindow  = new google.maps.InfoWindow({
        map: map,
        position: geolocate,
        content: 
                '<h1>Your Current Location is:</h1>'+
                '<h2>Latitude: '+latitude+'</h2>'+
                '<h2>Longitude: '+longitude+'</h2>'
    });
}
    
function handleError(error){
    var container = document.getElementById('map-canvas');
    switch(error.code) {
        case error.PERMISSION_DENIED:
            container.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            container.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            container.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            container.innerHTML = "An unknown error occurred."
            break;
    }
}
</script>
</body>
</html>

You can see in the above code that we have included enableHighAccuracy property to true so that the Geolocation tracks your location with high accuracy.

View Demo

I hope that you love this article.So please don’t forget to share it.

How you are going to use HTML5 Geolocation API?

Useful Resource

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

You may also like...

1 Response

  1. prabruaj says:

    Hi :

    I’ve tried this code it’s showing error as map not loading ,how to fix this…??

Leave a Reply

Your email address will not be published. Required fields are marked *