🤯 50% Off! 700+ courses, assessments, and books

Working with Geolocation and the Google Maps API

Aurelio De Rosa
Share

One of today’s most used APIs is the Geolocation API. Geolocation allows an application to determine your physical coordinates, and tailor the application to you. This has the potential to dramatically enhance your user experience. This article will show you how to use the Geolocation API together with the Google Maps API.

The Google Maps API lets you integrate the Google Maps service with your website. The examples in this article use version 3.10 of the API. The service is completely free, but you should subscribe to the APIs Console website to obtain your API key, and use it when you send a request to the service. If you need information about how to obtain the key, you can read the getting started guide. The API key allows you to monitor your application’s usage, and gives Google the chance to get in touch with you if necessary. Keep in mind that the Google Maps API has usage limits that you can increase for a fee. This article also assumes a basic understanding of Geolocation, which you can get by reading Using the HTML5 Geolocation API.

An Overview of the Google Maps API

This section covers the main classes and methods of the Google Maps API. There are many other objects and methods available, but discussing every aspect of the API is beyond the scope of this article. The most important and used class of the library is google.maps.Map. The Map class accepts two parameters that are an HTML element, that will contain the map, and a google.maps.MapOptions object. The MapOptions objects have many properties, but only the following three are required.

  • center: a google.maps.LatLng object (more on this later) used to set the initial map center.
  • mapTypeId: a google.maps.MapTypeId object, which is used to set the type of the map. For instance, you can see the map as a road map or a satellite map.
  • zoom: a positive number that sets the initial zoom of the map.

Apart from the several setters and getters for the class attributes, there are a couple of methods worth mentioning. The first is fitBounds(), which takes a LatLngBounds object as its only parameter. The LatLngBounds represents a rectangle built by specifying the south-west and north-east points. This sets the view of the map to contain the given bounds. The second method is panTo(), which accepts a LatLng object and changes the center of the map.

Another important class is google.maps.LatLng, which represents geographical coordinates in latitude and longitude. This class is used in almost every method of the Maps API. For example, we’ll use it to center the map on the user’s position. However, they’re also used to trace a route or to draw a polyline on the map.

Many maps contain markers which designate points of interest, such as a destination. To place markers on a map, you have to use the google.maps.Marker class. It creates a marker with the options (a google.maps.MarkerOptions object) passed to the constructor, and applies it to the specified map. The only required option is position, which sets the position of the marker.

The last class I’ll describe before showing you the example is the Geocoder. It lets you convert from an address to a LatLng object, and vice versa. It has an empty constructor and just one method, geocode(), that takes a GeocoderRequest object as a parameter, and a callback function in which you’ll read the results.

A Basic Example

Using the few classes described above, you’re now able to write a simple, yet nice, application. The example isn’t very hard to understand, but still uses all of the classes and methods discussed. The example retrieves the user’s position, and shows it using a marker on the map. The Geocoder service is used to retrieve the user’s complete address, and display it on the page. We’ll also use the accuracy parameter of the retrieved position to draw a blue circle around the location.

The first step to using the Maps API is to actually include it. This is very simple and consists of just adding the following line to your web page.

<script src="http://maps.google.com/maps/api/js?key=YOUR-KEY-GOES-HERE&sensor=true"></script>

Since Google Maps will still work without the key, and to avoid the long line in the example, simply write the following instead.

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>

Notice that both lines contain a sensor parameter. It must be included in the URL and set to true if you’re using a sensor (like a GPS), or false otherwise. You can read more on this at Loading the Maps API.

To build the example we’ll use two functions. The first one uses the user’s position to create a map and draw a circle around the user. The second function queries Google to retrieve the address of the user based on its location. Let’s see the key points of both.

var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

This simple line uses the latitude and longitude of a Position object to create the LatLng object. We’ll use this object in the rest of the function. In fact, it’ll be used in the MapOptions to set the center of the Map we’re building. As a container for the map, I’ll use a <div> element, with an id of map.

var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
}
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

Now it’s time to add the marker to the map to signal the user’s position. We’ll use the Google Maps default icon, but you can specify an image you like using the icon property or the setIcon() method.

new google.maps.Marker({map: mapObject, position: userLatLng });

At this point you could close the function and have a map displaying the user position with a simple marker. However, since in a desktop environment the accuracy could be very low, it would be nice to visualize it. We’ll accomplish this using the Circle class that, as you might guess, draws a circle on the map. It has a lot of properties to set the color, the opacity, the radius, and so on, but the most important property is the map object where it applies.

var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());

Please note that the last statement calls the fitBounds() method with the bounds taken from the circle. This is done to ensure that if the circle goes outside of the zoomed view, the map will be zoomed out accordingly to display the entire circle.

The second function, named writeAddressName(), takes a LatLng object and sets the location property to query the Geocoder service. In the callback function we’ll test if an error occurs. If an error does occur, it will be displayed. Otherwise, the formatted address is displayed.

function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": latLng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
document.getElementById("address").innerHTML = results[0].formatted_address;
else
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br />";
});
}

Putting it all Together

Given the code shown in the previous section, the final and completely working code is shown below.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": latLng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
document.getElementById("address").innerHTML = results[0].formatted_address;
else
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br />";
});
}

function geolocationSuccess(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
writeAddressName(userLatLng);

var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
// Draw a circle around the user position to have an idea of the current localization accuracy
var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
}

function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br />";
}

function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation)
{
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}

window.onload = geolocateUser;
</script>
<style type="text/css">
#map {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<h1>Basic example</h1>
<div id="map"></div>
<p><b>Address</b>: <span id="address"></span></p>
<p id="error"></p>
</body>
</html>

Conclusions

This article has explained several methods and properties of the most important classes in the Google Maps API. Moreover, we’ve shown how you can use them together with the Geolocation API to built a complete and functional service to track your user’s position and locate them on a map. Of course, you can do more a lot more than that as you’ll see in the next article on this amazing API.