Working with Geolocation and the Google Maps API

Share this article

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.

Frequently Asked Questions (FAQs) about Geolocation and Google Maps API

What is the Google Maps Geolocation API?

The Google Maps Geolocation API is a service that provides location data based on network infrastructure like cell towers and WiFi nodes. It doesn’t require the use of GPS, and it’s particularly useful in scenarios where GPS is unavailable or inaccurate. This API returns a location and accuracy radius based on the information you provide about cell towers and WiFi nodes.

How can I use the Geolocation API in my web application?

To use the Geolocation API in your web application, you need to make a POST request to the API endpoint. The request should include information about the cell towers and WiFi nodes that are visible to the device you’re trying to locate. The API will then return a location and accuracy radius.

What are the limitations of the Geolocation API?

The Geolocation API relies on the availability and accuracy of cell tower and WiFi node data. If this data is inaccurate or unavailable, the API may return inaccurate results. Additionally, the API may not work in all countries or regions due to local regulations or data availability.

How can I integrate the Geolocation API with the Google Maps JavaScript API?

You can integrate the Geolocation API with the Google Maps JavaScript API by using the location data returned by the Geolocation API to center a Google Map. You can also use the accuracy radius to draw a circle around the estimated location.

Can I use the Geolocation API for free?

The Geolocation API is a paid service. The cost depends on the number of requests you make. Google provides a pricing table on their website.

How accurate is the Geolocation API?

The accuracy of the Geolocation API depends on the accuracy and availability of cell tower and WiFi node data. In general, the API can provide a location within a few meters in urban areas. However, the accuracy may be lower in rural areas or areas with less network infrastructure.

Can I use the Geolocation API in a mobile application?

Yes, you can use the Geolocation API in a mobile application. However, keep in mind that the API requires network infrastructure data, which may not be available on all devices or in all locations.

What data do I need to provide to the Geolocation API?

You need to provide information about the visible cell towers and WiFi nodes. This includes the cell tower’s Mobile Country Code (MCC), Mobile Network Code (MNC), Location Area Code (LAC), and Cell ID (CID). For WiFi nodes, you need to provide the MAC address.

How can I handle errors from the Geolocation API?

The Geolocation API returns an error code and message in the response if there’s an error. You can handle these errors by checking the error code and message and taking appropriate action in your application.

Can I use the Geolocation API offline?

No, the Geolocation API requires an internet connection to work. It needs to send a request to the API endpoint and receive a response.

Aurelio De RosaAurelio De Rosa
View Author

I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.

functionsgeolocationIntermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week