Showing current location in browser using HTML5 Geolocation and Google Maps

HTML5 and Geolocation API

HTML5 comes with Geolocation API which allows user to provide their location to the web application. This is totally secure and user will always be asked for permission whether or not to provide information about their location.

The Geolocation API is provided with navigator.geolocation object of the BOM (Browser Object Model)

Current Position

To obtain the user's current location, you can call the getCurrentPosition() method of the geolocation object. It takes the success function as first parameter which setups position object in the function argument. The second parameter is an error function which setups error object in the function argument.

navigator.geolocation.getCurrentPosition(function(position) {
}, function(error) {

We can get the longitude and latitude from this position object as:

Watch Position

If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the watchPosition() function, which has the same input parameters as getCurrentPosition().

var watchID = navigator.geolocation.watchPosition(function(position) {

We can use the watchid value in tandem with the clearWatch() method to stop watching the user's location.


Demo Source Code

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">


<div id="geo-wrapper" width="600" height="400"></div>
<span id="geo-error"></span>

<script type="text/javascript" src=""></script>
<script src=""></script>

        $("#geo-error").html('Your browser does not support geolocation.');

function show_map(loc){

var lat = loc.coords.latitude;
var lon = loc.coords.longitude;

var lat_lon = new google.maps.LatLng(lat,lon);

mapholder = document.getElementById('geo-wrapper') = '250px'; = '500px';

var mapOptions = {

var map = new google.maps.Map(document.getElementById("geo-wrapper"), mapOptions);
var marker = new google.maps.Marker({position:lat_lon, map:map, title:"You are here.!"});


function show_map_error(error){
    var x = document.getElementById("geo-error");
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."


You can get the below code in Github Gist also -