Understanding Html5 GeoLocation API-Part II

Jul 31, 2013
Download Source

In the previous blog post we looked at basic GeoLocation API. If you are new to HTML5, refer my previous blog post on HTML5 GeoLocation before continuing with this blog post.

In previous post we saw how to access user's current location just by their browser. We saw three basic functions are available to us as part of GeoLocation API. All these three functions can be found in geolocation *object attribute of the *Navigator object.

  • getCurrentPosition
  • watchPosition
  • clearWatch

From above three we explored getCurrentPosition and saw how we can get users' location, specifically latitude, longitude, accuracy and bunch of other information. The next step once you have the location of the user is track where your users is going !!

Well not exactly, but sometimes you do want to keep track of users' location data, probably for your smart phone application to draw the path on the map or to see how much distance your user traveled. For these purposes, you constantly need to read user's location.

watchPosition and clearWatch functions will provide us the exact same features. Let's enhance on our previously created sample to test these two functions. First let's go ahead and modify our JavaScript to watch user's position. The function will return the ID of the watch you just added. You need to keep this ID around because in future if user does not want you to track him/her you will need this ID to clear the watch. As you might have guessed already, by calling clearWatch function passing this watchID.

GeoLocation wathcPosition

Once the page is modified go ahead and preview this page in your browser. As expected the browser should be asking user for his approval to track his location.

Accuracy

Once you approve, the successGeo function should be invoked looking at your speed and displaying the alert box as below. At the time of writing this I am not moving but actually sitting at my desk so my speed parameter will not return an actual number.

This watchPosition function periodically gets called when it detects change in user's location. And when you do no longer need to track user's location or user explicitly asks you to stop tracking him, you need to invoke clearWatch function passing the watID you received while setting up the watch by calling watchPosition.

Show user speed