I am currently building a new web product that relies on client location to a large extent. During the development I had to learn about the geo-location API for use within HTML5 compatible browsers, and thought I’d share how simple it is to use. Article first published on gooroo.io.
The use of GPS data has become second nature for most everyday tasks. The most common scenario of finding your way from A to B using GPS is obvious, but there are a lot of other uses as well. When you ask to find the nearest store on a company website, GPS is used. When you log into Facebook in a foreign country and you subsequently get ads for all of the Swedish natural foods you can eat, GPS is used. When you ask Google to remember where you parked your car, GPS is used. And many more ways.
Using GPS in your web app is not difficult, but there are a few points to note and some pit falls to avoid. This article will show you how to use the GPS hardware on the user’s device, and then take that one step further to use Google’s Map API to reverse geo-code the result and make it some kind of useful.
navigator.geolocation
The main API to use for accessing the GPS module on the device (usually a smartphone) is navigator.geolocation. This is part of the HTML5 specification and is supported by all major browsers. Although the API is supported on all modern browsers, it is recommended to still test for the presence of the API.
[code language=”javascript”]
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(callBack);
} else {
// Geolocation is not supported by this browser.
}
}
[/code]
In the code above, if the navigator.geolocation API is present, then we can call the getCurrentPosition method, which takes a callback function as argument to handle the result. The callback function will receive coordinates object, which can be queried to get latitude, longitude and accuracy.
[code language=”javascript”]
function callBack(pos) {
var crd = pos.coords;
console.log(‘Your current position is:’);
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
};
[/code]
This is all really straight forward and should not cause you any problems. One thing to note is you can only use navigation.geolocation over an HTTPS connection, as it had privacy implications asking users for their location.
watchPosition()
If you are interested in receiving continuously updated GPS coordinates, then you can use watchPosition() instead of getCurrentPosition(). This will return a new position every time the location of the device changes.
[code language=”javascript”]
function getLocation() {
if (navigator.geolocation) {
id = navigator.geolocation.watchPosition(callBack);
} else {
// Geolocation is not supported by this browser.
}
}
[/code]
It is used in the same way as getCurrentPosition(), and the callBack is called every time the position changes. To stop the watch function, call the clearWatch(id) function, where the id parameter is the id of the watch you set up with watchPosition().
[code language=”javascript”]
navigator.geolocation.clearWatch(id)
[/code]
Google Maps API
Now that you have the latitude and longitude of the user’s device, how can you actually use it? One of the ways to use the raw, but rather non-user friendly, GPS coordinates is through the Google Maps API.
First you need to get access to the Google Maps API, which is free and takes about 5 minutes to complete. Once you have access you need to create an API key for your current project, which authenticates you against the Google service.
Next, you add the following script tag to the bottom of your page, to load the Google Maps script for calling their API.
[code language=”javascript”]
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20async%3D%22%22%20defer%3D%22%22%20src%3D%22https%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2Fjs%3Fkey%3D%3Cyour%20key%20here%3E%26amp%3Bcallback%3DinitMap%22%3E%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
[/code]
Alright, we are now good to go with using the Google Maps with the coordinates received from the device.
[code language=”javascript”]
function callBack(position) {
var geocoder = new google.maps.Geocoder;
var latlng = { lat: parseFloat(position.coords.latitude), lng: parseFloat(position.coords.longitude) };
geocoder.geocode({ ‘location’: latlng },
function (results, status) {
if (status === ‘OK’) {
if (results[0]) {
geoText.innerHTML = results[0].formatted_address;
} else {
window.alert(‘No results found’);
}
} else {
window.alert(‘Geocoder failed due to: ‘ + status);
}
});
}
[/code]
This function is the callback for either getCurrentPosition() or watchPosition(). First, you get a reference to the Google Geocoder object, which we will use to get an address, if possible, from the coordinates we get from the navigator function. We need to pass the latitude and longitude as an object to the geocoder, which will either return 1 or more results, or none.
If we have results, then take the first one and show the formatted_address value. In this case we show it in an element called ‘geoText’. If we don’t have any results, then there are no nearby addresses or locations to show and we let the user know.
There it is. Using GPS data in your web app is really quite simple, and can add real value to your end users when used appropriate.