Over a million developers have joined DZone.

HTML5 Geolocation API with Google Maps

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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

In this post I will cover:

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

Getting Started with the HTML5 Geolocation API

The Geolocation API enables the browser to identify the location of the user using various mechanisms like the user's IP Address, GPS location, and cellular networks, depending on the device being used by the user. The location is identified as a pair of latitude and longitude values. Let's go ahead and create a simple HTML page and a JavaScript file to get the user's 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 that 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 for 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 Maps to Show Current Location

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

  1. Create a LatLng object using the latitude and longitude values obtained from the geolocation API.
    //Creating a new object for using latitude and longitude values with Google map.
    var latLng = new google.maps.LatLng(latitude, longitude);
    
  2. Create a MapOptions object.
    //Setting up the map options like zoom level, map type.
    var mapOptions = {
      center: latLng,
      zoom: 18,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
  3. Create a Map object and pass the HTML element (in our case, a div tag) to embed the map and MapOptions object created in the step above.
    //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);
    
  4. Create a MarkerOptions object indicating the location to be marked on the map.
    var markerOptions = {
      position: latLng,
      map: map,
      animation: google.maps.Animation.DROP,
      clickable: true
    }
    
  5. Create a Marker object and provide to 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.
    //Setting up the marker object to mark the location on the map canvas.
    var marker = new google.maps.Marker(markerOptions);
    
  6. Additionally, let's add a note window that will show something 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.
    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 the Example to Show Nearby Places on Google Maps

Now let's make use of the Places library and mark the nearby eat-outs on the map. This involves the following steps:

  1. Create an instance of PlacesService using the Map object created previously.
    var nearByService = new google.maps.places.PlacesService(map);
    
  2. Create a PlacesSearchRequest object to hold the information related to searching for places.
    var request = {
      location: latLng,
      radius: 1000,
      types: ['food', 'bakery', 'cafe', 
              'grocery_or_supermarket', 
              'meal_delivery','restaurant', 
              'meal_takeaway', 
              'shopping_mall']
    };
    
  3. Create a callback method that will be invoked on obtaining the Places result. This callback method will be provided with the results and the result status.
    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);
        }
      }
    }
    
  4. Register the callback with the PlacesService object and also provide the PlacesSearchRequest object created above.
    nearByService.nearbySearch(request, handleNearBySearchResults);
    

Let's look at the complete code that identifies the location, marks it on Google Maps 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);
  });
}

You can access this sample application live here.



Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}