Using Geolocation to Track Your Position

Using Geolocation to Track Your Position

Before we move on to including those extra features in the application, let’s make the modifications required to have the application use our current location instead of the static testing location that we have been using so far. Chapter 6 gave an introduction to the Geolocation API and the getCurrentPosition method. However, for Moundz it would

be great if we could track the user’s location rather than just get the location in a single- shot request.

This is actually very simple, and will involve replacing all of the code that we were using in the index.html initialize function with a run function in the moundz.js file as per the following code:

MOUNDZ = (function() { ...

// initialize variables var map = null,

... posWatchId = 0;

function run(zoomLevel) { // check that the watch hasn't already been set up // if it has, then exit, as we don't want two watches... if (posWatchId !== 0) {

return;

CHAPTER 10: Integrating with Social APIs

} // if

// create the watch posWatchId = navigator.geolocation.watchPosition(

function(position) { var pos = new google.maps.LatLng( position.coords.latitude, position.coords.longitude);

if (map) { map.panTo(pos); } else {

module.init(pos, zoomLevel ? zoomLevel : 15); } // if..else

findResources(function() { module.updateDisplay(); }); }, null, {

enableHighAccuracy: true }); } // run ...

var module = { ... run: run, ...

return module; })();

The run function defined in the preceding code is exposed through the MOUNDZ module and provides a simple interface for setting up the Geolocation watchPosition method.

The watchPosition method provides a mechanism for us to access the user’s position, and then to continue to monitor the position for changes. By monitoring the user’s position, we will be able to update the display as they move around, which is ideal when building games and other such interactive applications.

NOTE: As mentioned in Chapter 1, there is overhead involved when regularly accessing a device’s current position. So, while the preceding code is effective at monitoring the user’s position accurately, it’s important that we provide the ability to turn it off to allow people to conserve battery life on their mobile device.

Notice that in the preceding code we obtain an ID that relates to the position watch that has been created, and we will be able to use this later to stop monitoring the location.

CHAPTER 10: Integrating with Social APIs

While the watchPosition method differs in the number of times that the callback passed to it will be executed, the data returned in the callback is identical to the getCurrentPosition method, which we investigated previously. Basically, the watchPosition method will be called until the clearWatch method is called, whereas getCurrentPosition will execute once and once only. For instance, in the preceding code, the value that we assign to the posWatchId variable could be passed to the clearWatch function, and we would stop receiving location updates.

Additionally, the error callback and options parameters are the same. In this particular case, we supply the enableHighAccuracy option as true to indicate to the device that we would like to use the GPS in the device, rather than just using network triangulation.

In the callback within our run function, we simply map the returned latitude and longitude into a google.maps.LatLng object, and then pass that to our map as the position that we wish to use. As our findResources function works with the current center position of the map, all we have to do is call it once the position changes (and we have updated the map position to match), and relevant resources will be returned for our current location.

NOTE: While building location-based services and applications is interesting, testing them can be

a challenge. Often it is a case of writing some code, and then taking a device out into the field to ensure that the code is behaving as expected. If you find a problem, then it’s back to the desk to tweak the code. Then you rinse and repeat until everything works as expected.

Android actually offers some better-than-average tool support for building and testing geolocation-based applications. For more information on how to use the Android debug tools to simplify your development experience, including how to simulate GPS information and paths, have a look at the following article:

http://xpmobi.org/tutorials/android-emulator-geolocation-testing.html The downside, though, is that, without using these tools, the emulator will not return any useful

position information, and you will see a blank screen. So, if you don’t have experience using the tools, or you don’t have an Android device that you can test with instead, we would recommend working through the article and then carry on after that.

If you have a working Android device or have simulated geolocation events in the emulator when running the application, you should now see screens similar to the ones shown in Figure 10–11. The first of the screen captures shows the permission dialog that is displayed when the application requests the user’s position, and the second shows the screen once permission has been granted.

CHAPTER 10: Integrating with Social APIs

Figure 10–11. With geolocation data simulated in the emulator, you should see results similar to the images above.

With the application now tracking our position and providing information on resources around us, it’s time to implement some more of the game functionality.

Implementing a User Login

Download from Wow! eBook <www.wowebook.com>

Up until now, nothing in the game has required any knowledge of the user, but we are getting to the point where the user will probably want to mine some resources to start building their base.

Additionally, it’s unlikely that we’ll want to allow a user to walk around with a limitless amount of resources, so we are going to need to implement some limits. While the Geominer API will take care of most of the work for us, we are going to need to maintain

a session key on the client, which we will include with any requests that need information on who the current user is.

While the Geominer suite of tools could implement its own username and password management to meet this need, it’s definitely not the optimal solution. A much better solution is to integrate with an existing API that many users find themselves using on a day-to-day basis. As shown previously in Figure 10–7, the Twitter API ( http://dev.twitter.com) has been chosen to meet this need in version 1 of Geominer.

In the future, additional authentication options will most likely be added, including other social networks such as Facebook and the geosocial networks that actually provide the

CHAPTER 10: Integrating with Social APIs

check-in data. For the moment, though, Twitter provides a good middle ground in terms of an easy-to-implement solution with a reasonably strong existing user base.

NOTE: You may be wondering why Twitter was chosen as the authentication provider when the Geominer API presumably already talks to geosocial networks such as Gowalla and Foursquare. This is a fair question, given that both of those networks offer authentication support through their APIs. Primarily, this is because those geosocial networks still do not have as large a user base as Twitter.

Geosocial games like Moundz may interest users outside of the current geosocial networking users, so it is desirable for people to be able to access the game without needing a user account

on a specific geosocial network. In many respects, Twitter is neutral ground.

We now have a design decision to make: do we ask someone to log in at the point that authentication is required (i.e., when they start to collect resources), or do we create a welcome page and ask them to log in right from the start? There are definite merits to both solutions, and, while many would argue that from a usability perspective it would

be better to leave logging in only until required, for the sake of simplicity we will build a simple application splash screen with a very clear “Sign in with Twitter” button.