The Geolocation API is one of the most exciting new features of HTML5 for us GIS folk. In this section we’re going to look at how geolocation works, what capabilities it offers us and show how easy it is to build an application to retrieve the users location.
What is the Geolocation API?
So what is the Geolocation API? Well, the first thing to note is that Geolocation is not actually part of the HTML5 spec, but it’s mentioned so often in conjunction with HTML5 you could easily be fooled into thinking so. In a nutshell, the Geolocation API provides simple but powerful methods of both acquiring and using location data in web pages. That is, making web pages ‘location aware’.
The user’s location can be derived from a number of different sources depending on the technology they are using. For obvious reasons, this is mainly targeted at mobile devices – for the simple reason that they tend to change location frequently – but still works on the desktop.
The methods used for determining a user’s location include:
Geolocation is Device Dependent
Obviously this makes geolocation very device dependent.
The web browser or device works out what methods are open to it for determining location and then – importantly from a security perspective – the user is required to opt-in to start sharing their location data. What they opt in to is dependent upon the type of device they are using – whether it supports GPS, wi-fi, etc.
Because of these security considerations, most browsers will not let you run geolocation code on a local file system – it has to be delivered by a web server. So you will need to have access to a web server like IIS or Apache to start working with the Geolocation API.
Working with the Geolocation API
The Geolocation API is very simple to use. First, you need to make sure that the browser you are targeting supports Geolocation. You could go to a website like caniuse.com but clearly a more robust solution is to check programmatically at runtime. If geolocation is not supported you can fail gracefully or consider alternatives as previously discussed.
If geolocation is supported, you need to access the navigator.geolocation object which provides the methods that will determine the user’s location. Which method you call on the geolocation object will depend on whether you want to just grab the location as a one-off or monitor it continuously.
Whichever method you choose you will need to create callback functions to handle the results whether they be successes or failures. A callback function is a function that you pass by reference into a method. When the method completes it can then call back that function, passing in any required data.
Then, you need to do something with that data. And, being GIS folks we may just want to put it on a map!
Let’s build a simple geolocation application. We’ll start by building a simple HTML page.
As you can see from the above, my page consists simply of a heading and a blank paragraph element. I’ve given this element an ID of ‘myLocation’ so I can write information to it.
Within my body tag I am capturing the onLoad event. I want to make sure that all the DOM elements are loaded before any script I write attempt to interact with them. The event handler for this is the init() function in my script tags, which simply reports that the event has been fired and captured.
So the first thing we need to do is determine whether the browser supports the Geolocation API.
Within my init() function (code below) I have written some code to check for the existence of the navigator.geolocation object. If this object is null, the if statement will return false and write a message to the myLocation paragraph saying that Geolocation is not supported. But if the object exists, we can continue to work with the Geolocation API and we’ll write a message out to the user telling them so.
The next thing we need to do is call a method on our navigator.geolocation object and attempt to gauge the user’s current location.
There are two methods we can call to achieve this: getCurrentPosition() and watchPosition(). We’ll look at getCurrentPosition() first.
getCurrentPosition() is a one-shot: it retrieves the user’s location details once and that’s it. You might want to use this method if you are trying to locate the user’s nearest doctor or retail location.
watchPosition() is for tracking the user. It gets called continuously and returns new results every time the user changes position.
We’ll start off by using getCurrentPosition(). As you can see in the code below, I’ve created a local variable to store a reference to the navigator.geolocation object and specified two callback functions in the call to getCurrentPosition – one for success and one for failure.
I’ve stubbed out those functions with just an alert box to show us which function gets called. You’ll notice that both are passed an object as a parameter. These contain the results – in the case of successful location retrieval – or error details if otherwise. We’ll implement them in a bit.
First of all, let’s see what happens when we run this. I’m going to copy this html file to my web server – which I need to do for security reasons – and then launch it from that location in my browser.
I’m running Google Chrome, but your experience should be similar with any Geolocation-compliant browser.
The first thing I see is a notification that my web server (localhost) wants to track my physical location. If I press deny, my error handler gets called and I get a message saying that there is an error.
If I press Allow, then I get a message saying that there have been some results – in other words, the browser has managed to guess my position based on one of the device-specific options available to it.
Let’s now unpack those results and see what it came up with. If I analyze the object that gets passed through to my callback function I learn that it is an object of type GeoPosition and I can see how to unpack its coords collection and display my current position which is what I’ve done in the code example.
You’ll also observe that there are other entries there for heading, speed, etc which are not relevant to getCurrentPosition() but do make sense when we’re doing continuous monitoring using watchPosition(). The other main property on the Geoposition object is the timestamp. We can parse this to ascertain when location retrieval occurred.
Let’s see how accurate that result is, by plotting it on a map. At the time of writing I’m sitting with my laptop with wireless disabled in a town called Bicester (pronounced ‘Bista’) in the UK. Geolocation however, thinks I’m right in the center of the city of Oxford, about 12 miles away! It must be using my IP address in its calculations – not terribly accurate as you can see.
Now if I turn on Wireless, I get much better results. This time geolocation has positioned me about 20 meters away from my actual position.
However, if I connect my laptop to a GPS unit via Bluetooth I get much better results – bang on, in fact!
Tracking with watchPosition()
As mentioned earlier, the other method you can use to retrieve location details is watchPosition(). The syntax for watchPosition() is very similar to getCurrentPosition(). It requires callback functions for success and failure but also lets you specify an options object. This options object gives you access to three settings:
Timeout: the amount of time (in milliseconds) your application should wait to retrieve location details before raising an error
enableHighAccuracy: this setting is false by default. When set to true, geolocation will use every means at its disposal to retrieve the most accurate results. As a general rule, if you’re doing tracking with a mobile device (and it’s fairly unlikely you will be – think about it for a moment!) you should set this to ‘true’. Otherwise any GPS capability on your device may not be enabled and you’ll get sub-standard results.
maximumAge: This is the longest a current location value should remain cached before forcing retrieval of a new value.
Note that when we call the watchPosition() method we’re storing the return value in a variable called WatchID. WatchID contains a unique ID we can use to turn off tracking. We just call clearWatch() and pass in that ID to do this.
There are essentially three types of mobile application development including native, web, and hybrid solutions. What most people associate with mobile applications or apps are native applications. These are applications developed specifically for a particular mobile operating system platform. For example, most people associate apps in the Apple Store as native applications. As we’ll see this isn’t always the case though. Web applications developed for the mobile platform are run in the browser on the mobile device (Safari for example). Finally, Hybrid applications are a combination of the two, and as you’ll see they may well be the preferred method of mobile application development for most applications moving forward. In this post we’ll examine each of these application development types.
Native Mobile Applications
Native applications are developed specifically for the mobile device that it will be run on. For example, applications that you download from the Apple Store are often native applications for the iPhone or iPad. Different languages are used to develop these native applications. Applications developed for the iOS are created with Objective C, C, or C++. Android applications are developed with the Java programming language. These applications will run more efficiently than web or hybrid applications because they are compiled specifically for the operating system where they will run. Natively developed applications can also use all the phone’s features including the camera, geolocation, the users’ address book, and more. You don’t have access to all these functions when developing web mobile applications.
As I mentioned, native application development must use the language specific to the platform for which you’ll develop the application. The most common mobile development environments and their programming languages are illustrated below.
Native Application Development Process
The source code for natively developed application is written in the specific language for the platform being used. This course code is then compiled into an executable file. This is similar to traditional desktop application development. Any resources that need to be bundled with the application are then combined with the binary output from the compiler to produce a distribution package. Resources are typically things like images and icons that are used in your application. The distributable package is then ready for inclusion in the app store specific to your environment. App stores vary in their requirements for applications, but all include some sort of approval process which can be time consuming.
Image from Worklight.com
Native applications have full access to the operating system API on which they are developed. Your source code makes calls into the OS specific API to access the various services available on the platform. This will vary by platform, but all natively developed applications have full access to the functions provided. This includes functions such as data storage, location, camera, speaker, microphone, and others.
Image from Worklight.com
Native applications have a number of advantages. As I mentioned these applications have full access to all features of the mobile device so they are able to offer the full range of functionality. Native applications also do not have to be connected to the web to be used. They can be used in offline mode. In contrast, web applications always need access to the internet. This is changing though as you’ll see later. Finally, native applications get good visibility with consumers because they are distributed through the phone manufacturer’s app store.
There are also a number of disadvantages associated with natively developed applications. Because they are developed for a specific platform (operating system and device) the number of users that can be reached is restricted. For example, if you develop an application for Android devices, Apple users will not be able to access the application unless you specifically write the application for the iOS. This can lead to a lot of duplicate work. Third party approval can also be barrier. You have to wait for approval for the application to be published to the app store so you have limited control over the timing of the distribution. All of this means you’re duplicating work on different patterns. This can be time consuming and costly.
Mobile Web Application Development Process
The web application development process is quite different from native applications. Applications are run through the browser on the mobile device. In this case there is no need for an app store since the application runs through the browser instead. One of the drawbacks of using this type of development process is that you don’t have access to the full array of operating system functions provided by the mobile device. In fact, this set of functions is quite limited on many devices.
Image from Worklight.com
There are some disadvantages to using a mobile web application development process. The primary disadvantage is that you can’t make use of many of the phone’s built in features such as the camera or the address book. They also can’t be deployed to the phone’s marketplace which limits the visibility of the application in some ways.
Hybrid Application Development Process
Image from Worklight.com
PhoneGap has two primary tasks. First, it enables you to take an existing code base and deploy to multiple mobile platforms. This is quite important as it removes the need to re-develop an application for each platform that you intend to use. PhoneGap also provides access to the operating system functionality provided by the mobile device.
Image from Worklight.com
HTML5 is in widespread use in mobile web application development. The top supported features of HTML5 on mobile devices include audio and video, geolocation, offline web application support, web storage, CSS3 selectors, and 2D animations. For an extensive look at mobile compatibility with HTML5 features please visit the link provided on this slide.
This smaller footprint is a great choice for mobile applications including the iPhone and iPad. There are two primary differences between the standard and compact builds of the API. First, the compact build only loads objects that are needed for your application. For example, if you don’t need a Calendar widget then it’s not loaded. The second difference is that the compact build only loads 32 code modules instead of the 80 modules loaded with the standard Dojo build. If you need to use a code module that is not downloaded as part of the compact build then you can use dojo.require to load the specific module you use. You’ll also notice that various user interface components have been altered to make them easier to use on a mobile platform.
So, at some point you will need to make a decision on what type of application development process you intend to use for your application. Your choice may vary depending upon the needs of the application. Considerations include time, budget, and resources available to develop each solution. In general, native applications cost more and take more time to get to market, but the user experience is often better in terms of functionality and performance. Web applications, while they tend to cost less and can be developed more quickly don’t have quite the user experience as they don’t run as fast nor do they have access to the full capabilities of the platform. Hybrid applications provide an excellent alternative by combining the best features of both platforms.
Building Mobile ArcGIS Server Applications
It’s obviously a lot to learn, but our new Building Mobile ArcGIS Server Applications course is designed to get you up to speed with developing hybrid mobile GIS applications. By the end of this class you will be well on your web to developing some great mobile GIS applications. The first session begins April 16th, 2012.
The first session of our Building Mobile ArcGIS Server Applications course will be offered beginning April 16th and runs through May 18th.
There are a tremendous number of mobile application development platforms including iPhone, iPad ,Android devices, Windows 7 devices, Blackberry, and others. Developing applications for each of these platforms can be a time consuming, frustrating process. It is not uncommon to develop the exact same application multiple times; once for each supported platform. What a waste of resources!
* HTML5 and CSS3
* DojoX Mobile
* Capstone Project
Get free access to the first module in our Programming the ArcGIS Server API for Flex here.
Price for each course is $567 through Oct. 26th. Price increases to $715 after this date.
We’re keeping the survey open through July 31st. If you haven’t already participated in the survey please take a few moments to do so and forward this to your colleagues.
To date we have had 731 respondents. Here are some of the highlights:
You can also customize the look of the window as well as the content. In this post you will learn how easy it is to programmatically add this new widget to your application. You can also use the ArcGIS.com map viewer to create popup windows. This post is the first in a three part series. This first post will cover the basics of adding a Popup window to your application while the second and third posts will cover advanced customization topics.
Reference the Widget
You’ll first want to add the popup stylesheet to your application as seen below:
Next, reference the Popup widget using dojo.require.
Creating the Popup
The constructor for a Popup widget takes two parameters: options and an HTML source reference to where the popup will be placed. The ‘options’ parameter is optional and can be used to customize the look of the popup window.
In the code example below you’ll see that we simply provide a ‘null’ reference for the options object. This simply means that we’ll use the default options provided by the Popup. The srcNodeRef is going to be a <div> container that we create to hold the content.
The second line of code highlighted below indicates that when the map is initially created the new Popup widget, stored in a variable called ‘popup’, will serve as the info window for the application.
Finally, the dojo.place method is used to define where the popup will appear which in this case is the <div> container that we created. Place the popup under the map’s root element. This ensures that the coordinate space used by the popup for positioning aligns with the map’s coordinate space.
Adding just the lines we’ve already discussed is enough to create a basic Popup window. Many times that’s all you need for your application, but you can also customize not only the look of the window but also the content.
Formatting with the PopupTemplate Class
Popup content can be formatted using the PopupTemplate class. PopupTemplate inherits from the InfoTemplate class. A code example showing how to create an instance of PopupTemplate is provided below. This object can be used to create a title and description for the window along with a means for defining the fields that should be visible along with their labels and formatting. You can also define whether attachments should be visible (showAttachments:<boolean>) as well as images, charts, and other media that will be part of the window. We’ll examine some of these advanced customization techniques in our second post.
In this code example above we’ve simply defined a title for the window along with the fields that will be visible and stated that we want attachments to be loaded if they exist.
A PopupTemplate is then referenced from the ‘infoTemplate’ option when defining a new FeatureLayer as seen in the code example below.
In the next post we’ll examine several ways that you can customize the look and content of your popup windows.
The next session of this course will run from June 6th – July 15th. Register by April 15th to take advantage of our early registration price of $499. The regular course price is $715 so this is a great deal.
The newly revised course includes nearly 1000 pages of lecture notes, and 36 exercises.
What have past students of this class said about the course?
“Liked the combination of slides and exercises. I learn best by example – your approach lets me type in code, and if it doesn’t work I can check solution. More examples the better for me, everything I’ve ever learned about GIS programming came by starting with an example and modifying it. Thanks again, will likely take a course in the future.” — Joe Spollen, President, Geodatamodelers
“I’m impressed with the quality of the course and materials. I’m recommending your courses to my clients. I think they’re the best thing out there.” — Stephanie Stanfield, Fargeo
Our Spring 2011 training schedule has been released. Most of these courses are taught in a web based environment but we do have one traditional face to face session of GIS Programming 101 for ArcGIS 10 scheduled for the King County GIS Center in Seattle, WA. Here is the upcoming schedule:
I’m doing this because I think the book will be better based on feedback that I get from my readers and of course it will serve as motivation for finishing the book!
I am not going to release the chapters in chronological order so the first chapter to be released in public beta is not the first but rather the third covering maps and layers.
Download the chapter, read it, and tell me what you think. Either by posting a comment below or by contacting me directly through eric at geospatialtraining.com.
Here’s a tentative list of all the chapters in the book:
As of now I don’t know in which form this book will be published, but I’ll keep you informed as things progress.
If you have a request for something that you want me to include in the book, or any thoughts or questions about it, please contact me.