Home » HTML5 » HTML5 Geolocation API with Google Maps

About Mohamed Sanaulla

Mohamed Sanaulla

HTML5 Geolocation API with Google 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
//Creating a new object for using latitude and longitude values with Google map.
var latLng = new google.maps.LatLng(latitude, longitude);
    1. 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
};
    1. 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.
//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);
    1. 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
}
    1. 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.
//Setting up the marker object to mark the location on the map canvas.
var marker = new google.maps.Marker(markerOptions);
  1. 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.
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.
var nearByService = new google.maps.places.PlacesService(map);
    1. Create a PlacesSearchRequest object to hold the information related to searching the places.
var request = {
  location: latLng,
  radius: 1000,
  types: ['food', 'bakery', 'cafe',
          'grocery_or_supermarket',
          'meal_delivery','restaurant',
          'meal_takeaway',
          'shopping_mall']
};
    1. 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.
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);
    }
  }
}
  1. Register the callback with the PlacesService object and also provide the PlacesSearchRequest object created above.
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.

Reference: HTML5 Geolocation API with Goolge Maps from our WCG partner Mohamed Sanaulla at the Experiences Unlimited blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
4 Comments Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Iginla.omotayo
Omotayo
5 years ago

Woah, this is so explanatory and amazing how you simplified it. You ll make a good tutor.

Very helpful

Bernie
Bernie
4 years ago

Hi there, thank you, I really can use that.

Is there any way to get the state, province out of this script?

Many thanks and regards from South Africa
bernie

pablo
pablo
4 years ago

Very well done best I found and thorough explanation. Is there an easy way to modify it so there is a drop down for the PlacesSearchRequest object types? so for example where————– types: [‘food’, ‘bakery’, ‘cafe’, —–the user could select a drop down for say types: [‘gas’, ‘automotive’, ‘car repair’…………. and so on from a drop down list?

Aemiro Mekete
Aemiro Mekete
4 years ago

It is an Amazing Tutorial please Keep it up. Thanks