HTML5 Geolocation API with Goolge Maps

I have been reading Head First HTML5 and read about the Geolocation support in HTML5 and also went through the example they have shared about using the Google Maps with HTML5 geolocation API. It was an interesting example and I went a step further and enhanced the example to show some eat outs around the current location. For this I made use of the Places library which comes with the Google Maps API.

In this post I will cover:

  1. Getting started with HTML5 Geolocation API.
  2. Integrating Google map to show current location.
  3. Enhancing to show nearby places on Google map.

Getting started with HTML5 Geolocation API

The Geolocation API enables the browser to identify the location of the user using various mechanisms like IP Address, GPS, Cellular networks depending on the device being used by the user. The location is identified as a pair of latitude and longitude values. Lets go ahead and create a simple html page and a javascript file to get the user location:

<html>
  <head>
    <meta charset="utf-8">
    <title>Where am I?</title>
    <script src="myLoc.js"></script>
  </head>
  <body>
    <!-- The location will be updated in the below div -->
    <div id="location">
      Your location will go here.
    </div>
  </body>
</html>

And the javascript code which updates the above html with the user location is:

//myLoc.js
window.onload = getMyLocation;

function getMyLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayLocation);
  } else {
    alert("Oops, no geolocation support");
  }
}

//This function is inokved asynchronously by the HTML5 geolocation API.
function displayLocation(position) {

  //The latitude and longitude values obtained from HTML 5 API.
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;

  //Setting the latitude and longitude values in the div.
  var div = document.getElementById("location");
  div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}

In the above javascript code the navigator object’s geolocation property is used to obtain the location of the user. If the browser supports the HTML5 Geolocation API then it will ask confirmation from the user about accessing the user’s location. Once the location has been identified it asynchronously invokes the callback displayLocation registered with the Geolocation API. The callback does nothing special other than updating the html with the latitude and longitude values.

Integrating Google map to show current location

To integrate the Google Map, one should start with the Getting started document of Google Map API which shows how to get a Google API Key and also some sample example to start using Google Maps API. One would have to do the following to mark the current location on the Google map:

  1. Create an LatLng object using the latitude and longitude values obtained from the geolocation API
  2. //Creating a new object for using latitude and longitude values with Google map.
    var latLng = new google.maps.LatLng(latitude, longitude);
    
  3. Create a MapOptions object.
  4. //Setting up the map options like zoom level, map type.
    var mapOptions = {
      center: latLng,
      zoom: 18,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
  5. Create a Map object and pass the html element (in our case div tag) to embed the map and MapOptions object created in the step above.
  6. //Creating the Map instance and assigning the HTML div element to render it in.
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    
  7. Create a MarkerOptions object indicating the location to be marked on the map
  8. var markerOptions = {
      position: latLng,
      map: map,
      animation: google.maps.Animation.DROP,
      clickable: true
    }
    
  9. Create a Marker object and provide it the MarkerOptions object and the Map object created in the steps above. This Marker object uses the MarkerOptions object to get the location information and then the Map object to mark the location.
  10. //Setting up the marker object to mark the location on the map canvas.
    var marker = new google.maps.Marker(markerOptions);
    
  11. Additionally lets add an note window which would show some thing about the place when the user clicks on the location. This is achieved by creating an InfoWindowOptions object and using it to create an InfoWindow object. This note window should be opened when the user clicks on the marker which can be done by adding an event listener for click event.
  12. var infoWindowOptions = {
      content: content,
      position: latLng
    };
    
    var infoWindow = new google.maps.InfoWindow(infoWindowOptions);
    
    google.maps.event.addListener(marker, "click", function() {
      infoWindow.open(map);
    });
    

The complete code which shows the location on the Google map is given below:

<!-- index.html -->
<html>
  <head>
    <meta charset="utf-8">
    <title>Where am I?</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
    <script src="myLoc.js"></script>
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
  </head>
  <body>
    <div id="location">
      Your location will go here.
    </div>
    <div id="map-canvas">
      Google Map will go here!.
    </div>
  </body>
</html>

The javascript code:

//myLoc.js
window.onload = getMyLocation;
//Note that map has been globally declared.
var map;
function getMyLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayLocation);
  } else {
    alert("Oops, no geolocation support");
  }
}

//This function is inokved asynchronously by the HTML5 geolocation API.
function displayLocation(position) {
  //The latitude and longitude values obtained from HTML 5 API.
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;

  //Creating a new object for using latitude and longitude values with Google map.
  var latLng = new google.maps.LatLng(latitude, longitude);

  showMap(latLng);
  createMarker(latLng);
  
  //Also setting the latitude and longitude values in another div.
  var div = document.getElementById("location");
  div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}

function showMap(latLng) {
  //Setting up the map options like zoom level, map type.
  var mapOptions = {
    center: latLng,
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  //Creating the Map instance and assigning the HTML div element to render it in.
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
function createMarker(latLng) {
  //Setting up the marker object to mark the location on the map canvas.
  var markerOptions = {
    position: latLng,
    map: map,
    animation: google.maps.Animation.DROP,
    clickable: true
  }
  var marker = new google.maps.Marker(markerOptions);

  var content = "You are here: " + latLng.lat() + ", " + latLng.lng();
  addInfoWindow(marker, latLng, content);

}

function addInfoWindow(marker, latLng, content) {
  var infoWindowOptions = {
    content: content,
    position: latLng
  };

  var infoWindow = new google.maps.InfoWindow(infoWindowOptions);

  google.maps.event.addListener(marker, "click", function() {
    infoWindow.open(map);
  });
}

Enhancing to show nearby places on Google map

Now lets make use of the Places library and mark the nearby eatouts on the map. This involves the following steps:

  1. Create an instance of PlacesService using the Map object created previously.
  2. var nearByService = new google.maps.places.PlacesService(map);
    
  3. Create a PlacesSearchRequest object to hold the information related to searching the places.
  4. var request = {
      location: latLng,
      radius: 1000,
      types: ['food', 'bakery', 'cafe', 
              'grocery_or_supermarket', 
              'meal_delivery','restaurant', 
              'meal_takeaway', 
              'shopping_mall']
    };
    
  5. Create a callback method which will be invoked on obtaining the places result. This callback method will be provided with the results and the result status.
  6. function handleNearBySearchResults(results, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          var place = results[i];
          createMarker(place.geometry.location, place);
        }
      }
    }
    
  7. Register the callback with the PlacesService object and also provide the PlacesSearchRequest object created above.
  8. nearByService.nearbySearch(request, handleNearBySearchResults);
    

Lets look at the complete code which identifies the location, marks it on the Google map and also marks nearby eat outs on the map.
The html for this is:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Where am I?</title>
    <script type="text/javascript"
    src="https://maps.googleapis.com/maps/api/js?sensor=true&libraries=places,weather"></script>
    <script src="myLoc.js"></script>
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
  </head>
  <body>
    <div id="location">
      Your location will go here.
    </div>
    <div id="map-canvas">
      Google Map will go here!.
    </div>
  </body>
</html>

The javascript code for this is:

window.onload = getMyLocation;

var map;
function getMyLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayLocation);
  } else {
    alert("Oops, no geolocation support");
  }
}

//This function is inokved asynchronously by the HTML5 geolocation API.
function displayLocation(position) {
  //The latitude and longitude values obtained from HTML 5 API.
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;

  //Creating a new object for using latitude and longitude values with Google map.
  var latLng = new google.maps.LatLng(latitude, longitude);

  showMap(latLng);

  addNearByPlaces(latLng);
  createMarker(latLng);
  
  //Also setting the latitude and longitude values in another div.
  var div = document.getElementById("location");
  div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}

function showMap(latLng) {
  //Setting up the map options like zoom level, map type.
  var mapOptions = {
    center: latLng,
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  //Creating the Map instance and assigning the HTML div element to render it in.
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}

function addNearByPlaces(latLng) {

  var nearByService = new google.maps.places.PlacesService(map);

  var request = {
    location: latLng,
    radius: 1000,
    types: ['food', 'bakery', 'cafe', 'grocery_or_supermarket', 'meal_delivery','restaurant', 'meal_takeaway', 'shopping_mall']
  };

  nearByService.nearbySearch(request, handleNearBySearchResults);
}

function handleNearBySearchResults(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(place.geometry.location, place);
    }
  }
}

function createMarker(latLng, placeResult) {
  var markerOptions = {
    position: latLng,
    map: map,
    animation: google.maps.Animation.DROP,
    clickable: true
  }
  //Setting up the marker object to mark the location on the map canvas.
  var marker = new google.maps.Marker(markerOptions);

  if (placeResult) {
    var content = placeResult.name+"<br/>"+placeResult.vicinity+"<br/>"+placeResult.types;
    addInfoWindow(marker, latLng, content);
  }
  else {
    var content = "You are here: " + latLng.lat() + ", " + latLng.lng();
    addInfoWindow(marker, latLng, content);
  }

}

function addInfoWindow(marker, latLng, content) {
  var infoWindowOptions = {
    content: content,
    position: latLng
  };

  var infoWindow = new google.maps.InfoWindow(infoWindowOptions);

  google.maps.event.addListener(marker, "click", function() {
    infoWindow.open(map);
  });
}

Some of the recommended books:

You can access this sample application live here.

Advertisements

8 thoughts on “HTML5 Geolocation API with Goolge Maps

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s