Adobe
Products

Top destinations

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • SiteCatalyst
  • Students
  • Elements family

Adobe Creative Cloud

  • What is Adobe Creative Cloud?
  • Design
  • Web
  • Photography
  • Video
  • Students
  • Teams
  • Enterprise
  • Educational institutions

Design and photography

  • Photoshop
  • Illustrator
  • InDesign
  • Adobe Muse
  • Lightroom

Video

  • Adobe Premiere
  • After Effects

Web development and HTML5

  • Edge Tools & Services [opens in a new window]
  • Dreamweaver
  • Gaming [opens in a new window]

Adobe Marketing Cloud

  • What is Adobe Marketing Cloud?
  • Digital analytics
  • Social marketing
  • Web experience management
  • Testing and targeting
  • Media optimization

Analytics

  • SiteCatalyst
  • Adobe Discover
  • Insight

Social

  • Adobe Social

Experience Manager

  • CQ
  • Scene7

Target

  • Test&Target
  • Recommendations
  • Search&Promote

Media Optimizer

  • AdLens
  • AudienceManager
  • AudienceResearch

Document services

  • Acrobat
  • EchoSign [opens in a new window]
  • FormsCentral [opens in a new window]
  • SendNow [opens in a new window]
  • Acrobat.com [opens in a new window]

Publishing

  • Digital Publishing Suite

  • See all products
Business solutions

By business need

  • Digital analytics
  • Digital publishing
  • Document management
  • Media optimization
  • Social marketing
  • Testing and targeting
  • Video editing and serving
  • Web development [opens in a new window]
  • Web experience management
  • See all business needs

By industry

  • Broadcast
  • Education
  • Financial services
  • Government
  • Publishing
  • Retail
  • See all industries
Support & Learning

I need help

  • Products
  • Adobe Creative Cloud
  • Adobe Marketing Cloud
  • Forums [opens in a new window]

I want to learn

  • Training and tutorials
  • Certification [opens in a new window]
  • Adobe Developer Connection
  • Adobe Design Center
  • Adobe TV [opens in a new window]
  • Adobe Marketing Center
  • Adobe Labs [opens in a new window]
Download
  • Product trials
  • Adobe Flash Player
  • Adobe Reader
  • Adobe AIR
  • See all downloads
Company
  • Careers at Adobe
  • Investor Relations
  • Newsroom
  • Privacy
  • Corporate Social Responsibility
  • Customer Showcase
  • Contact us
  • More company info
Buy
  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers
  • Adobe Marketing Cloud sales [opens in a new window]
Search
 
Info Sign in
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Welcome,
My Adobe
My orders
My information
My preferences
My products and services
Sign out
My cart
Privacy My Adobe
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out Privacy 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
Promotions
Estimated shipping
Tax
Calculated at checkout
Total
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
DreamweaverHTML5JavaScriptmobile
Was this helpful?
Yes   No

By clicking Submit, you accept the Adobe Terms of Use.

 
Thanks for your feedback.

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

  • Using CSS3 transitions: A comprehensive guide
  • The pursuit of simplicity
  • An Overview of Brackets' Code Architecture
  • Backbone.js Wine Cellar tutorial – Part 1: Getting started
  • JavaScript design patterns – Part 1: Singleton, composite, and façade
  • Getting started with PhoneGap in Eclipse for Android
  • Unit test JavaScript applications with Jasmine
  • Backbone.js Wine Cellar tutorial – Part 2: CRUD
  • Build a Hangman game with HTML5 Canvas, JavaScript, and CSS – Part 1: Creating the interface
  • Introduction to web typography and @font-face

Products

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • Digital Publishing Suite
  • Elements family
  • SiteCatalyst
  • For education

Download

  • Product trials
  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR

Support & Learning

  • Product help
  • Forums

Buy

  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers

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 © 2013 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy | Cookies

Ad Choices

Reviewed by TRUSTe: site privacy statement