What is Geolocation API?
Implementing the Geolocation API.
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.
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.
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

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; }
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..)
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
Merci pour ce tutorial
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