Languages7 Key Ways To Use The Geolocation API

7 Key Ways To Use The Geolocation API

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

Many websites don’t need to know anything about the geographical location of their visitors. In certain cases, however, this knowledge can be useful and can be used to enhance the user experience. This knowledge can also be used to integrate special features into your application. Consider, for example, a company selling some electrical equipment. By knowing the user’s geographical location you can suggest the nearest store where they can visit, and purchase the products. To provide such suggestions it is important to capture the user’s location. To that end, the Geolocation API allows you to do just that. This article examines seven key things you should know about the Geolocation API in order to use it in your web applications.

1. Geolocation API Allows You to Develop Location Aware Web Applications

The Geolocation API allows you to retrieve an end user’s geographical location. The Geolocation API is exposed through the window.navigator.geolocation object and can be programmed using JavaScript. It allows you to perform two essential functions:

  • Retrieve user’s current geographical location.
  • Monitor user’s location as he moves from one place to another.

Using Geolocation API you can provide location aware services to the end users. For example, a company selling electrical goods may inform their website visitors about the nearest store based on the end user’s location. Similarly, a travel agency may inform their website visitors about the distance between the user’s location and a destination. The Geolocation API simply tells you about the user’s location. How to use that information depends on the application requirements. A variety of sources may supply location data to the Geolocation API depending on the device being used. Some of them include IP address, GPS, Wi-Fi and GSM / CDMA.

2. Geolocation API Uses Latitude and Longitude Coordinate System

We use standardized units such as Meter and Kilogram to express length and weight values. On the same lines, the geographical location of a user must be expressed in some standard form. In day to day life we express a geographical location in terms of street address, city, country and postal code. However, such details can’t be used for mathematical calculations. For example, you can’t use the addresses of two locations to calculate the distance between them.

That is why the Geolocation API uses the geographic coordinate system consisting of Latitude and Longitude of a location. A latitude coordinate specifies the north-south position of a point on the Earth’s surface whereas a longitude coordinate specifies the east-west position of a point on the Earth’s surface. The latitude and longitude values can be specified in decimal / minute / second (DMS) format or decimal degrees. For example, latitude and longitude of Mumbai in DMS format is 18° 55′ N and 72° 54′ E respectively. The same values can be expressed as 18.91667 and 72.9 in decimal format.

The Geolocation API requires latitude and longitude values in decimal format. 

3. Sharing of Location Information is Controlled by the End User

Just because you used Geolocation API in a web page doesn’t mean you will be successful in retrieving the user’s location. That’s because the user must allow the browser to send your location information. Whenever you access any webpage that makes use of Geolocation API, the browser prompts you for your permission. The following figure shows how Chrome seeks your approval.

Chrome Approval

Once you allow a web page to grab your location your preference is stored by the browser for later requests. Of course, you can change the settings if you so wish. The following figure shows how Chrome allows you to clear the settings.

Clear Settings

So, whether to share location with your application or not is controlled by the end user. You should provide appropriate error handling code or alternate functionality keeping this in mind.

4. getCurrentPosition() Allows You to Capture User Location

To retrieve a user’s location at a given point in time you use getCurrentPosition() method of the geolocation object. The getCurrentPosition() accepts a success function, an error function and a set of configuration options. The success function is called when the user location information is successfully retrieved. The success handler receives a position object that contains details of the user location. The error function is invoked if there is any error retrieving the location information. It receives an error object supplying more details about the error.

The following piece of code shows how getCurrentPosition() can be used:

 $("#button1").click(function () {
   window.navigator.geolocation.getCurrentPosition(function (pos) {
     var latitude = pos.coords.latitude;
     var longitude = pos.coords.longitude;
     alert(latitude, longitude);
   }, function (err) {
     alert(err.code + " : " + err.message);
   });
 });

The above code shows the click event handler of a button. It calls the getCurrentPosition() method on the window.navigator.geolocation object. The success function receives a position object as its parameter. The actual latitude and longitude coordinates are obtained using coords.latitude and coords.longitude properties. The error function displays the err.code and err.message properties of the error object.

5. watchPosition() Allows You to Monitor User Location

The getCurrentPosition() method returns a user’s location at the time when the method was called. In some cases you may need to continuously monitor a user’s location as he moves from one place to the other. This task can be accomplished using watchPosition() method. The watchPosition() method accepts success and error functions as before and returns an ID representing the current watch operation. This ID can be used with another method – clearWatch() – to stop monitoring the user location. The following piece of code shows how watchPosition() and clearPosition() can be used:

var watchId;
 
 $("#button1").click(function () {
   watchId = window.navigator.geolocation.watchPosition(function (pos) {
     var latitude = pos.coords.latitude;
     var longitude = pos.coords.longitude;
     //do something with location
   }, function (err) {
     //display error message
   });
 });
 
 $("#button2").click(function () {
   window.navigator.geolocation.clearWatch(watchId);
 });

As you can see, watchPosition() is quite similar to getCurrentPosition() in terms of method parameters. However, it returns watchId. The watch ID is stored in a global variable. The clearWatch() method accepts the ID of the watch operation and stops the monitoring operation.

6. Geolocation API can be Integrated with Mapping Applications

The Geolocation API can be used in many innovative ways. One such use is to integrate it with mapping applications such as Google Maps and Bing Maps. For example, you may use Geolocation API to retrieve a user’s location and then mark that location on a map to indicate their current position. You may also plot a driving route from their current location to some destination on a map. The following figure shows a user’s current location plotted on Bing Maps.

Current Location

Usually these mapping applications provide their own API to developers and you may need an API key to call them in a web page. As a basic example of how this integration can be done read this article.

7. There is no Inbuilt Way to Calculate Distance Between Two Locations

A common requirement while working with Geolocation API is to calculate the distance between two points. There is no inbuilt way to accomplish this task and you need to do some complex calculations yourself. There are two approaches you may take for distance calculation – client side calculation and server side calculation. In the former approach you calculate distance between two locations using Geolocation API and mathematical calculations done at the client end. As an example of how this is done read this article. If you are using some server side processing engine (ASP.NET, for example) then you may have access to some server side library that calculates the distance between two geolocation points. For example, .NET developers can use the System.Device.Location.GeoCoordinate class to calculate distance between two geolocation points. 

Summary

Geolocation API allows you to develop location aware web applications, applications that make use of a user’s geographical location in some way or another. Geolocation API is exposed through the geolocation object. The three methods of this object – getCurrentPosition(), watchPosition() and clearWatch() – allow you to work with a user’s location information. You can use Geolocation API in many innovative ways and can also integrate them with mapping applications.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories