How to Use HTML5 Geolocation API – A Detailed Tutorial

Today, we will create web pages that are location aware.  We will utilize the Geolocation API to fetch the user Coordinates. To make things even better we will capture the user location and then display it on Google Maps. 

 

Before we begin, lets talk a bit about the Geolcation API.

 

What is Geolocation API?

The geolocation API allows you to easily fetch the geographical position of a user. If the browser support Geolocation API, one can easily get the Longitude and Latitude just using Javascript. The Geolocation API uses  multiple sources to determine the most accurate position of the user.   The location accuray depnds upon the best location source available.
The most common sources of location information are IP address, Wi-Fi and Bluetooth MAC address, radio-frequency identification (RFID), Wi-Fi connection location, or device Global Positioning System (GPS) and GSM/CDMA cell IDs. Here is link to Wiki

                                                                      View Demo

 

Implementing the Geolocation API.

Using the Geolocation API is quite straight forward. We first create a Geolocation object and then use the getCurrenPosition method to fetch user coordinates.
Here is the sample Code. I will be explaining the code in detail.

 

HTML Markup

<!doctype html > 
<html lang="en" > 
<head> 
<title> How to find location of a user using HTML5 Geolocation? </title> 
<meta charset="utf-8" > <link href="css/style.css" rel="stylesheet" type="text/css" /> 

<script type="text/javascript" >     

window.onload = getLocation;      

var geo = navigator.geolocation;     /*     Here we will check if the browser supports the Geolocation API; if exists, then we will display the location     */    

function getLocation() {       
    if( geo ) {    
        geo.getCurrentPosition( displayLocation );       
           } 
           else  { alert( "Oops, Geolocation API is not supported");        
           }     
}         

/*     This function displays the latitude and longitude when the browser has a location.     */   

    function displayLocation( position ) {         
        var latitude = position.coords.latitude;        
        var longitude = position.coords.longitude;            
        var div = document.getElementById( 'location' );     
        div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;    
                                } 
</script> 

</head> 

<body>     
<div class="container" >        
<h3> How to find location of a user using HTML5 Geolocation? </h3>              
<div id="location" >            
You are at Latitude: _________, Longitude: _________         
</div>    
</div> 
</body> 
</html>

The code is as simple as it gets. As you can see:,

  • We first create a Geolocation Object geo;
  • We then check if the browser supports Geolocation API . If the API is not supported then we simply return an error.
  • If API is supported then we call the getCurrentPosition Method and pass displayLocation() function as a callback.  Pls refer to this link if you want to know more about the getcurrentPosition method.
  • The displayLocation()  function takes position object as parameter and print out the user coordniates on the Web Page.
 Take note that with Geolocation API ; sharing the location is always opt-in. In other words the geolocation API cannot access location data without explicit permission of the user.
So, when you run the HTML page for the first time, the browser will ask if you want to share your location with the webpage. Assuming that you click on Yes, then this is what you will see.

Latitude and Lonitude

Figure 1: Shows the latitude and longitude of my current location

The webpage simply displays the user coordinates.  Now lets display the coordinates on Google Maps

Mapping your Position

The Geolocation API is fairly easy – it gives you a way to detect where you are, but it doesn’t provide you with any tools to see your location. We need a third-party tool like Google Maps to  display our current location on the map.

Basically we will create a Google Maps object and then pass our location coordinates using map options.
The following code now displays the location on a google Map. I will be explaining the code in detail.

HTML Markup


<!doctype html >
<html lang="en" >
<head>
<title> How to find location of a user using HTML5 Geolocation? </title>
<meta charset="utf-8" >
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="http://maps.google.com/maps/api/js?sensor=true" > </script>
<script type="text/javascript" >
window.onload = getLocation;

/*
Here we will check the browser supports the Geolocation API; if exists, then we will display the location
*/
var geo = navigator.geolocation;
function getLocation() {
if( geo ) {
geo.getCurrentPosition( displayLocation );
} else {
alert( "Oops, Geolocation API is not supported" );
}
}

/*
This function displays the latitude and longitude when the browser has a location.
*/
function displayLocation( position ) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

var div = document.getElementById( 'location' );
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;

// Call showMap function once we've updated other div's on the page
displayMap( position.coords );
}

// Global Variable that will hold Google Map
var map;
/*
This method is used to display Google Map.
*/
function displayMap( coords ) {
var googleLatAndLong = new google.maps.LatLng( coords.latitude, coords.longitude );

var mapOptions = {
zoom: 10,
center: googleLatAndLong,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};

var mapDiv = document.getElementById( 'map' );
map = new google.maps.Map( mapDiv, mapOptions );
}
</script>
</head>
<body>
<div class="container" >
<h3> How to find location of a user using HTML5 Geolocation? </h3>

<div id="location" >
You are at Latitude: _________, Longitude: _________
</div>

<div id="map" > </div>
</div>
</body>
</html>
  • We create a function displayMap() and call it inside the displayLocation() function.  The displayMap() function take the location coordinates as the parameter. 
  • The displayMap() function is actually responsible for creating the google maps.  
  •  We create a Google Map object and pass the coordinates (provided by the geolocation API) using the Map Options. Pls take note that first we need to convert the coordinates into a format which google map understand.  We are using google.maps.LatLng class for that 
Also don’t forget to include the Google Map Library in the header :) .
We will now add some CSS to make our page more presentable. Create another file as style.css and include it in the webpage.

CSS Rules

* {
    margin: 0 auto;
    padding: 0;
}

body {
    background-color: #F2F2F2;
}

.container {
    margin: 0 auto;
    width: 920px;
    padding: 50px 20px;
    background-color: #fff;
}

h3 {
    text-align: center;
    margin-bottom: 50px;
}

p {
    margin: 20px;
}

#location {
    margin-bottom: 30px;
}

#map {
    width: 800px;
    height: 400px;
}
This is how the web page appears now. As you can see a map is created with our coordinates at the center

 

Google Maps                                                 Figure 2: Shows current location inside Google Maps

Adding a Marker on our Location.

It would be more useful if we could see exactly where we are located on the map. If you’ve previously used Google Maps, then you must be familiar with the markers / pins used to mark the location.

We will now create a addMarker function which will do 3 things:  :

  • It will create a marker on the specified coordinates. The coordinates as passed through Marker Options.
  • We then create an info window on our location Pls take note that by default the info window is not visible. We need to call the open method on InfoWindow. (Official Doc)  
  • We will then add click handler to our Marker.  The click handler will execute infoWindow.open(map,marker). So whenever someone clicks on the marker, the info window will open.

Here is the code for addMarker function. Just include it after the displayMap function

/* 
 This function creates a marker, an InfoWindow and add a click handler on the Marker.
 */
 function addMarker ( map, latlong, title, content ) {
 var markerOptions = {
 position: latlong,
 map: map,
 title: title,
 clickable: true
 };
var marker = new google.maps.Marker( markerOptions );
var infoWindowOptions = {
 content: content,
 position: latlong
 };
var infoWindow = new google.maps.InfoWindow( infoWindowOptions );
google.maps.event.addListener( marker, 'click', function() {
 infoWindow.open(map);
 });
 }

Now call the addMarker function from displayMap.

Add this to the bottom of your displayMap() function:

var title = 'Your Location';
var content = 'You are here: ' + coords.latitude + ', ' + coords.longitude;
addMarker( map, googleLatAndLong, title, content );

Reload the page and now you will see a map with a marker with your location on it. Try clicking on the marker, you will get a pop-up window with your latitude and longitude.

This is great, because now you know exactly where you are (just in case, you were lost or something..)

Google Maps with Marker                                                 Figure 3: Shows your location on the marker

Conclusion

Geolocation API is cool and useful at the same time.  Once you have a the location one can really tailor the user experience.

Credit

This tutorial uses some of the code in one of the HeadFirst Series Books. Thanks to Mohit for helping out

 

About Ankit

Founder of Spice Forms.
Spice Form is a Drag n Drop tool to create powerful web forms in minutes.

Comments

  1. Merci pour ce tutorial

  2. Thanks a lot for the tutorial its awesome but i have to now store this data in the cookie then upon user login or user registration i have to tie this location to that user. How would i go about doing that? i can save the cookie in session but for some reason i just cant figure out how to do that while using your script :/ Any ideas would be much appreciated

Speak Your Mind

*