Firefox OS Tutorial : Episode 5 : Location, Location, Location

Welcome to Episode 5 of the Firefox OS Tutorial. This series will take you through the steps to writing Firefox OS Apps that are location aware. What this means is that your application can interact with the GPS receiver that is present on the Firefox OS Device, retrieve the current position (latitude, longitude) and thereby help you write location based applications.

Prerequisites

  • You have setup your machine with the Firefox OS Simulator. If not, you can check out Episode 1, which takes you through the entire setup.
  • You have a basic understanding of writing Firefox OS Apps. If not, I strongly suggest to refer to earlier episodes, especially Episode 2, that covers how to write your first Firefox OS App.

What this Episode covers

  • What are Location Based Applications
  • HTML5 Geolocation API
  • Sample Firefox OS Application that covers using HTML5 Geolocation API
  • Sample Firefox OS Application that uses HTML5 Geolocation API to retrieve current position (latitude, longitude) and plot that on the Google Map

Episode 5 in Action

Let us check out the application in action first. This will help you understand what we shall be achieving by the end of this blog post.

What we shall write is a mobile application that will retrieves our current position and on successfully getting the current position from the GPS receiver on the Firefox OS phone, it will plot that location on a Google Map.

All right then, the first screen of the mobile app is shown below:

ep5-screen6

When we click on the as shown below:

ep5-screen7

Let’s get going with the code. Note that the example screenshots are from the Firefox OS Simulator running locally. So you can use your Firefox OS Simulator to run all the examples.

Download Full Source Code – Episode 5

I suggest that you begin with a full download of the project source code. Since the project depends on libraries like jQuery and jQuery Mobile, it will save you the hassle of downloading the dependent libraries.

Go ahead & download the code from : https://github.com/rominirani/LocateMe

Extract all the code in some folder. For e.g. on my machine, the code is present in e:\firefox-os-blog\episode5\LocateMe but it could be any directory of your choice. You should see a folder structure inside of LocateMe, that looks something like this:

ep5-screen8

Location Based Applications

Smartphones come with a GPS receiver that is able to provide you with the current position of the device. Location Based Applications are those applications that make use of the device location to give you better localized data. For e.g. if you are searching for restaurants in an area where you are currently taking a walk, it makes sense for the application to utilize the current location via the GPS and provide your eateries that are in and around you within a certain radius.  Location is here to stay and the ability of an application to know the users location is key.

HTML5 Geolocation API

HTML5 has support for determining the location of the user via the Geolocation API. It supports both a one time location retrieval and also continuous location retrieval depending on the need of your application. Geolocation support is determined via the navigator.geolocation object in the browser. Firefox OS supports the HTML5 Geolocation support and you will find similar support in most mobile browsers and desktop browsers out there. Check out the following table.

In this episode, we shall be looking at the one-time location retrieval via the HTML5 Geolocation API. While the continous location retrieval is also available, I suggest that you should have a good use case for the same because you need to keep in mind that the easiest way to drain out the phone battery is via a badly written GPS application.

Application 1

In this application, we shall first look at the HTML5 Geolocation API so that we can familiar with its usage. In the next application, we shall cover using that location to plot on the Google Map.

Let us check out the application running on the Firefox OS Simulator. The first screen is shown below and is a simple screen with a button labeled LocateMe.

ep5-screen1

When you click on the LocateMe button, it will popup a permission screen as shown below. This permission screen is not part of the application but is a standard one that all browsers display to ask for permission of the user.

Let us spend a minute on why this is needed. Determining the location of a device behind the scenes has privacy implications and the recommended practice is always of asking the user for permission, also known an opt-in. HTML5 Geolocation specification makes it clear that browsers need to ask the user for permission before determining the location. Each browser does this differently via a bar that typically appears just under the address bar and the Firefox OS behavior is what you are seeing below.

  • If you say “Yes” to the browser asking for permission, then it goes about its work to determine the location.
  • If you refuse permission, then the error callback method (which we shall see in a while) and it will have the value PERMISSION_DENIED. So in well-written mobile applications, you should be prepared for a user refusing to permission to get the location.
  • Once you give the browser permission, it can remember that option on subsequent location determination as you can see from the Remember my choice toggle button below. You can always go into the Device Phone Settings and clear the permission.

ep5-screen2

OK, so we can safely click on the Allow button as shown above. This will use the HTML5 Geolocation API, retrieve the current latitude, longitude and show that as demonstrated below.

ep5-screen3

Side Note: In your Firefox OS Simulator, you will notice that there is an Action Bar at the bottom as shown below. The last button which is highlighted here is the Location button. By default, the Firefox OS Simulator also gives you a custom co-ordinate. You can use one too and give a latitude/longitude of your choice. What that means is that if you use a custom coordinate, then whenever you try to retrieve the location using the HTML5 Geolocation API then it will return you the same coordinate, again and again.

ep5-screen4

But if you want it to determine the current co-ordinates, then you should toggle it to the Use my current coordinates. In the Firefox OS Simulator, you will find that it will try to use your current Internet to determine the location. In case you do not have connectivity, then I suggest you use the custom coordinates, so that you can atleast get a result and the HTML5 Geolocation API works.

ep5-screen5

Let us look at the code now.

Application 1 – manifest.webapp

The first thing we should discuss is the manifest file. This should be familiar now and it has the standard attributes like name, version, etc.

What is specific to our example and important is to note that we have an additional permission for geolocation on line #17.

Application 1 – index.html

Next up is the index.html page and it is a simple jQuery Mobile page. It contains a button LocateMe on Line #21. The button click handler and all relevant source code is present in app.js as referenced on Line #10.

Application 1 – app.js

This file contains the code that is invoked when the button is clicked on Line #3. 

Let us discuss the source code in detail now since it contains the HTML5 Geolocation JavaScript API.

  • The function findMyCurrentLocation() is invoked when the Button is clicked.
  • As mentioned before, Geolocation support in the browser is present via the navigator.geolocation object. So we first initialize a geoService object on Line #7.
  • We determine if the browser support the HTML5 Geolocation API on lines #8-12. If it does not, we simply display that message else we invoke the getCurrentPosition method on the navigator.geolocation object.
  • Notice that we have provided it 2 parameters. The first parameter is the success callback function. This function will be invoked when the application is able to determine the location. The second parameter is the error callback method. This method will be invoked when the browser is unable to determine the location.
  • If the browser is able to determine the location, the success callback method is invoked. In our case, it is the showCurrentLocation method on Line #14. A parameter of type Position is passed into this success callback method. The Position object has an attribute coords of type Coordinates that contains all the information about the Location that you want. We extract out the latitude and longitude as shown in the code and we display that. In addition to them, you can also extract out other attributes like altitude, speed, heading, etc.
  • If your location could not be determined, the error callback method is invoked. In our case, it is the errorHandler method on Line #18. A parameter of type PositionError is passed to it. You can use this PositionError method to determine the exact reason why it failed via the code and message attributes. It could have 3 values:  PositionError.PERMISSION_DENIED, PositionError.UNAVAILABLE and PositionError.TIMEOUT. So if you need to do some custom handling or error message depending on the error, you can check the value and then give a custom message instead of the message attribute.

Note: We can also provide a 3rd parameter to the getCurrentPosition method. This parameter is of type PositionsOptions, where we specify extra criteria to help guide the Geolocation API for the kind of location data characteristics. For example, we could have passed {enableHighAccuracy : “true”} , which tells the API to use the highest possible accuracy. Other attributes that you could specify are timeout and maxAge. Refer to the specification for more detail.

Application 2

We will now extend our code to not just display the current latitude, longitude but to also show the Google Map with a Marker that will represent our current location.

Earlier in this post, we had demonstrated Application 2 in Action, so I am not repeating the screenshots over here.

The manifest file for this application remains the same except for the launch_path property values that now points to map.html 

Do note that in the Github project I have provided only a single webapp.manifest file, so if you plan to swap between index.html and map.html, then you should modify the launch_path property value to either index.html or map.html. 

Application 2 – map.html

In the HTML, we are using jQuery Mobile again, but this time it has 2 pages. The home page contains a simple button and instruction to invoke the HTML5 Geolocation API. And then there is a map-page defined, that will be navigated to automatically to display the Google Map. All relevant source code is present in map-app.js as referenced on Line #10.

Application 2 – map-app.js

The heart of the application is in the map-app.js file below:

Let us look at the code in detail. It is similar to the earlier one till the point that we get the Latitude and Longitude in the showCurrentPosition method. We do the following:

  • We create a Google Maps LatLng object based on our current latitude and longitude. Line #18
  • We set up an options object that Google Maps needs. For e.g. we specify the Map Type as ROAD, set a Zoom Level and also pass in the center point to our location. Line #20-24
  • Next thing is to set our div for the map to occupy the entire screen space accept for the header title. So we retrieve the handle to the content area and set it to the entire screen height minus 50 pixels. Line #25-28
  • We initialize the Google Map by passing it the parameter for our content div along with the options object. Line #31
  • Then we switch to the second page in the application i.e. map-page. Line #34
  • Finally we create the Marker for our position and drop it (animate) into the Map. Line #35-40

Local Installation and Testing

This completes our discussion of writing Firefox OS applications that utilize the HTML5 Geolocation API. Now comes the part of seeing it actually work. All we need to test out this application is:

  1. You should have installed the Firefox OS Simulator add-on in your Firefox Browser.
  2. A working internet connection from your machine.
  3. You should have downloaded/written the application as described above. We will assume that the index.html and manifest.webapp file are present in a folder named LocateMe. You should navigate to your own directory structure when called to later.

Steps to install the application in your Firefox OS Simulator should be familiar to you now. Simply launch the Firefox OS Simulator in your Firefox Browser. From the Dashboard, click on the Add Directory button and point it to the manifest.webapp file for the LocateMe application. On successful validation, the application will be installed and it will come up in your OS Simulator. For sample screenshots, refer to the section at the beginning of this blog post for Episode 5 in Action.

Next Steps

I encourage you to enhance the current application by using the current location to do interesting things like retrieving nearby points of interest : hotels, movie theatres, etc. You could even write a Weather Application that detects where you are and retrieves the current weather conditions via a public API.

Coming up Next

The next episode will take you through another HTML5 API : Local Storage. This is a very critical API to help build persistence (saving data) in your application. Local Storage is also one of the key techniques to enable your application to work offline.

Till the next time, stay tuned and give me feedback.

Complete Firefox OS Tutorial

Feedback

I would love to hear your feedback on the series so far. Do put your feedback in the comments. If you are facing issues, use the comments to let me know about it, I will do my best to answer your queries. And by putting in your issues within this thread itself, it will help build collective knowledge that could help other readers.


Firefox OS

Advertisements

23 thoughts on “Firefox OS Tutorial : Episode 5 : Location, Location, Location

  1. Nice tutorial, however, I prefer not using jquery, as you know, we try to make apps with the least size possible so when it’s loading it has the best possible performance.
    and while jquery libraries aren’t small, using native Javascript is my way on the go 🙂

  2. Hi Romin,
    The tutorials are extremely useful. I appreciate the way each episode explains everything in detail.

    Rgds,
    H Jain

  3. Hi Romin,
    Why did you need 2 pages in the Application 2?
    What the purpose is in HOME page?
    Is there a way to show google map in this map-canvas?
    I tried to substitute the $content[0] by document.getElementById(‘map-canvas’) but nothing happen.

    1. 1. You are right – the application does not really need 2 pages, it is just there for demonstration purpose. Maybe you can put some other functionality if you want on the first page, etc .. some search parameters, etc. But for the purpose of the example, yes .. you do not need 2 pages. And by that definition, the map-canvas element is not really needed then on the first page.
      2. Yes – you should be able to show the map in the map-canvas on the first page. I do not see anything wrong with what you have done. I think the issue is that you will need to provide it some height otherwise the height of the div element is not much for the map to be visible. If you notice on the second page, we are not just loading the map but we are also setting the height of the div to the page size – 50 (for the header). So try doing that and I believe the map should show up.

  4. Hi, Romin, thank you for nice tutorial. However I can’t display the google map when I ran the app in Firefox OS Simulator. An error has been shown in log: “ReferenceError: google is not defined”. But I can open map.html normally in firefox browser and the google maps will be shown. Do you have an idea?

  5. Hi, Romin i have the same problem with the Firefox OS Simulator (“ReferenceError: google is not defined”. But also I can open the map.html in firefox browser normally). Do you know how to fix that problem? thanks…

  6. Hi Romin,
    I have a problem with your application 2 LocateMe. The application can not load Google Maps API.
    The console displays: Content Security Policy: The page’s settings blocked the loading of a resource at https://maps.googleapis.com/maps/api/js?sensor=true (“script-src app://80ddc3d2-fe06-437e-bfb8-73db554e4550”).
    Do you know how to fix this problem?
    Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s