Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / HTML5, CSS3, and JavaScript /

Using the Geolocation API

by Ryan Stewart

Ryan Stewart
  • blog.digitalbackcountry.com

Content

  • Getting started with Geolocation
  • Handling location data
  • Tracking constant location
  • Where to go from here

Created

3 May 2011

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
Dreamweaver HTML5 JavaScript mobile

Requirements

Prerequisite knowledge

Basic HTML and JavaScript.

User level

Intermediate

Required products

  • Dreamweaver (Download trial)

Sample files

  • geolocation.zip

The Geolocation API is one of the most simple but also one of the most powerful new related technologies to HTML5. It allows you to figure out where your users are and then provide them information about what's around them. And with the explosion of smartphones, nearly everyone carries a GPS with them that you can use as part of your HTML and JavaScript applications. You can download the complete code for the example discussed in this article above or view it here.

Note: You can follow the tutorial with any version of Dreamweaver or a text editor.

Getting started with Geolocation

The first thing to understand about using the Geolocation API is that it can mean a few different things depending on the device you're calling the API from. For example, on a mobile device, which has a GPS chip built in, in most cases the Geolocation API will call the GPS chip directly through the browser so that you get the exact longitude and latitude coordinates from the GPS chip in the phone. In some cases, however—say if GPS is turned off, but the phone still has location enabled—the API will return an approximate latitude and longitude based on other data the phone has like cell-phone towers or WiFi hotspots in the area.

That second method is how Geolocation works on devices that don't have built-in GPS, like on a laptop, for example. Because of this, the Geolocation API can be different depending on the browser that you're using to access it. Chrome and Firefox, for example, use the Google location API which uses a bunch of data including IP address and nearby Wi-Fi hotspots to return a latitude and longitude.

The good news is that as a developer, the API doesn't really change much at all depending on how the location is being retrieved. You still get a latitude and longitude object and you even get a property that will show you how accurate the GPS reading is.

Getting your position

The Geolocation API is one of the simplest and most powerful APIs in HTML5. To get location from a user, simply check that geolocation is supported and then call getCurrentPosition() on the navigator object:

if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError); } else { alert("Your browser or device doesn't support Geolocation"); }

That's the basic API. Note parameters in the above snippet: In this case both are the callback functions that will be called when there is a successful geolocation call or when something goes wrong.

Privacy and permission

Before I dissect the data that comes back when you make a call to the Geolocation API, it's probably a good idea to address privacy and permissions. The spec for the Geolocation API is very specific about making sure that the API requests the user's permission before doing anything. This happens in a number of ways depending on your device, but in general it will appear as a prompt whenever the getCurrentLocation function is called. Your users are the ones who have ultimate control over whether or not you'll be able to access their locations so it's important to be clear what you're requesting and why. Figure 1 shows an example of the dialog box users see when you request their locations:

Figure 1. The dialog box that Chrome uses to prompt for location access
Figure 1. The dialog box that Chrome uses to prompt for location access

If a user denies access, you'll get an error and your error callback function will be called. I'll show you how to how to deal with that below.

Handling location data

If your geolocation call is successful, you'll get back a geoposition object, which has a bunch of location-related information. The data is contained within the coords object of the event and you can retrieve the following properties:

  • latitude
  • longitude
  • accuracy
  • altitude
  • altitudeAccuracy
  • heading
  • speed

The event also includes a timestamp object that provides the date and time of the GPS fix.

So to display the current location on the screen, in a successful callback function you can do something as simple as this:

function onGeoSuccess(event) { alert(event.coords.latitude + ', ' + event.coords.longitude); }

And you can use any of the properties above if they're available. Not all devices will provide all of those properties, so if you're trying to use them and they aren't there, the browser or device you're on doesn't support them.

Dealing with Errors

Sometimes you won't get a GPS fix for a number of reasons. If that happens, and you've specified an error function when you called getCurrentLocation , you'll get some information about what the problem is. The event that is returned is a PositionError event and it has two properties, a code and a message . Code is an integer which represents the error code and message is a human readable message that explains what the code is. You may encounter four different types of errors:

  • Code 0 - UNKNOWN_ERROR: The browser doesn't have an answer for what went wrong.
  • Code 1 – PERMISSION_DENIED : This is when the user disallows you from accessing their location
  • Code 2 – POSITION_UNAVAILABLE : If the GPS chip isn't able to get a fix or if the location service is unavailable for any reason.
  • Code 3 – TIMEOUT : The GPS wasn't able to get a location in the time specified. This can be customized as you'll see below.

So you can create an error function that provides some information as to what caused the geolocation call to fail.

function onGeoError(event) { alert("Error code " + event.code + ". " + event.message); }

Customizing the Geolocation request

You can also customize some of the properties of the request by using a PositionsObject and setting a few properties. That can then be passed along with the success and failure callbacks in the getCurrentPosition function.

The PositionsObject has three properties:

  • enableHighAccuracy
  • timeout
  • maximumAge

enableHighAccuracy can force the geolocation API to only use the GPS satellites and not use Wi-Fi or a cell tower. timeout lets you specify the number of milliseconds before the API gives up trying to get a location, and maximumAge will cache the last known location in memory for a set number of milliseconds and will then use that data next time the API is called if it is less than the maximumAge .

Tracking constant location

getCurrentLocation is great if you want to grab the location of your user in that specific moment in time, but what do you do if you want more consistent updates? That's where you can use the watchLocation function instead. watchLocation takes the same parameters as getCurrentLocation but your success callback function will be called whenever the user's location changes. One thing to note is that you can't control how often the API will request the location because the device figures out the ideal time between API checks and returns the data accordingly.

When you use watchLocation it will return a number. That number is what you use to stop the API from continuing to request location data whenever it changes.

var watchID; function getLocationConstant() { if(navigator.geolocation) { watchID = navigator.geolocation.watchPosition(onGeoSuccess,onGeoError); } else { alert("Your browser or device doesn't support Geolocation"); } } function stopGetLocation(event) { navigator.geolocation.clearWatch(watchID); }

Where to go from here

At this point you should have a good background on adding geolocation to your own HTML appliations. Definitely check out the rest of the HTML5 Developer Center for great ways to add additional features to your web applications.

More Like This

  • Developing HTML5 games with Impact JavaScript game engine and Dreamweaver CS5.5
  • Introducing the HTML5 storage APIs
  • Introducing theexpressiveweb.com beta
  • CSS3 basics
  • Adobe, standards, and HTML5
  • Real-time data exchange in HTML5 with WebSockets
  • Backbone.js Wine Cellar tutorial – Part 1: Getting started
  • Backbone.js Wine Cellar tutorial – Part 2: CRUD
  • Object types in JavaScript
  • Pseudo-classical object-oriented programming in JavaScript with Minion

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement