GPS Geolocation in Safari on iPhone OS 3.0

I just updated my iPhone to the shiny new OS 3.0. Apple did a great job addressing a few shortcomings and adding new features. Others have already told about the common features so I won’t rehash them here.

But let me tell you about my favorite new feature: Safari can now get your GPS location via javascript! This is usually referred to as geolocation. You can easily grab the current location or get periodic updates.

Okay, so I’m excited over what may seem like an obscure geeky feature, but I think it’s a big deal.

Why GPS in Safari is a Big Deal

  1. Location aware Web pages: Have you ever gone to a company’s Web site to find their nearest location? You usually have to type in your zip code. But what if you’re traveling and don’t know your zip code? Safari knowing your location solves that problem.

  2. Location aware Web applications: It’s fairly easy to create Web content looks and behaves like an iPhone application. Now those can take advantage of location information.

    For example, I’ve been working with a company on an iPhone Web application that interacts with their internal customer database. Field reps can now easily find customers within a certain radius of the rep’s current location who meet various other criteria.

Web Geolocation Privacy and Standards

Don’t worry, all of this is built with good privacy controls. You are asked permission before your location data is revealed to a site. For convenience, it stops asking about a particular site after you have approved it a few times.

These location features are based on the upcoming Geolocation API Specification. Because it’s not just a proprietary Safari thing it should get widespread adoption. In fact, it’s already built into the latest Firefox 3.5 beta.

Web Geolocation Sample Code

The specifications do a good job of explaining the parts so no need to go over all of that. However, it’s worth pointing out how to check and see if geolocation features are available or not and take appropriate action. For example, you may only want to show GPS options if it can actually be used. This simple snippet will do the job.

if (navigator.geolocation) {  
	/* Code if geolocation is available. */  
} else {  
	/* Code if geolocation is not available */
}

Let’s put it all together in a simple Web page that displays all of the geolocation variables for your current location. The code is below or you can try my geolocation test page from your iPhone.

(Yes, you’ll probably want to use modern DOM techniques for a real project. The purpose of this is just to show a simple working example.)

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
		<title>Geolocation Test</title>
 
		<script language="javascript" type="text/javascript">
			function getLocation() {
				// Get location no more than 10 minutes old. 600000 ms = 10 minutes.
				navigator.geolocation.getCurrentPosition(showLocation, showError, {enableHighAccuracy:true,maximumAge:600000});
			}
 
			function showError(error) {
				alert(error.code + ' ' + error.message);
			}
 
			function showLocation(position) {
				geoinfo.innerHTML='<p>Latitude: ' + position.coords.latitude + '</p>' 
				+ '<p>Longitude: ' + position.coords.longitude + '</p>' 
				+ '<p>Accuracy: ' + position.coords.accuracy + '</p>' 
				+ '<p>Altitude: ' + position.coords.altitude + '</p>' 
				+ '<p>Altitude accuracy: ' + position.coords.altitudeAccuracy + '</p>' 
				+ '<p>Speed: ' + position.coords.speed + '</p>' 
				+ '<p>Heading: ' + position.coords.heading + '</p>';
			}
		</script>
	</head>
	<body>
		<script language="javascript" type="text/javascript">	
			if (navigator.geolocation) {  
				document.write('<p><input type="button" onclick="getLocation()" value="Show Geolocation Information" /></p>');
			} else {  
				document.write('<p>Sorry, your device or browser software does not appear to support geolocation services.</p>');  
			}  
		</script>
 
		<div id="geoinfo"></div>
	</body>
</html>

I can’t wait to see some of the great things others will create by combining Web sites with location. And it will only get better as more devices become location aware. Be sure to let me know of good location-aware sites and web apps you run across.

Now go create something cool!

27 Responses to “GPS Geolocation in Safari on iPhone OS 3.0”

  1. Posted by: Té Baybute - 06/24/2009

    Hi, I work for the website http://www.greenmap.org . we are working on a mobile website version for our Open Green Map platform. We would love to include location services in the web app and we are looking to find a site that we can test the feature. Your test site seems to be down, do you have it available elsewhere or can you direct us to another site with this feature? Thanks, Te

  2. Posted by: Doug Smith - 06/24/2009

    I think my host did have a very short bit of down time but it seems to be working now. You can always grab the code from the blog post and run it on your own Web server. It’s only a single page and doesn’t require anything special on the server side.

    If you were just seeing the message “Sorry, geolocation services are not available,” then that is simply because the page detected that your device or Web browser wasn’t capable of doing geolocation. I’ll have to update that message to be more descriptive.

  3. Posted by: Kent Brewster - 06/24/2009

    Hmmm … Lattitude, longitude, and accuracy are all there, but I’m getting a bunch of nulls for everything from altitude on down. Would this be a 3GS-only function, you think?

  4. Posted by: Doug Smith - 06/24/2009

    @Kent, I initially thought those might be 3G S only too, especially heading because of the compass. I do occasionally see altitude and altitude accuracy values show up on my 3G, though. I also tried loading the page while I was moving, thinking it might need motion to get the speed value, but it never showed anything.

    I got a friend to try it with his 3G S and those variables didn’t get populated there either. My best guess is that Apple got the basics in there but didn’t implement the full specification yet. Anyone else get a different result?

  5. Posted by: Kent Brewster - 06/25/2009

    Okay, thanks. Playing around with it now; will try it from a moving car and see what happens.

  6. Posted by: Té Baybute - 06/25/2009

    I haven’t had a chance to try it yet but I am wondering if the feature will work with wifi

  7. Posted by: Doug Smith - 06/25/2009

    @Té Baybute, It doesn’t matter what type of connection you have. The technology just lets Safari make use of the geo information from the iPhone hardware.

  8. Posted by: Steve Stedman - 06/30/2009

    @Doug, I’m right there with your enthusiasm for built-in geolocation. The convergence of browser location awareness (Firefox 3.5 has geolocation too) and more refined mapping APIs (Gmaps v3 is slimmer/more OO) is very exciting. Replicating the native iPhone Maps app is now ridiculously easy: http://plebeosaur.us/you-are-here-with-safari-on-iphone/

  9. Posted by: Doug Smith - 06/30/2009

    @Steve, Sweet demo! I was just thinking about doing a tracker example and now I don’t have to. It shouldn’t take too much to extend that concept to upload positions to a server for some “where’s Doug” tracking fun.

  10. Posted by: Doug Smith - 07/06/2009

    Here are a few more links that might be helpful for some:

  11. Posted by: Terry - 08/17/2009

    WOW!!! This is an amazing demo! Thanks so much!!!!! It’s saved me hours, days and possibly months of pain!!!

    :)

    Terry

  12. Posted by: KommandorKeen - 09/25/2009

    Thanks for the starters. If I can get this location into a custom google map with my own layers in there for estuarine currents I have an app for displaying currents in a river onboard a sailing boat using realtime model output and I haven’t had to program the Iphone at all.

    Simon

  13. Posted by: znelson - 10/02/2009

    Hey – glad I stumbled onto your page but this totally doesn’t work on my 3G. I can press the “Show Geolocation Info” button all day long, nothing happens. Did something change?

  14. Posted by: Doug Smith - 10/02/2009

    I just tried it on a 3G and a 3GS with no problem. Double-check your iPhone settings under General to make sure you have Location Services turned on.

  15. Posted by: Eddie - 11/07/2009

    Yet another awesome feature of the iPhone and apple OS, for a learning web developer this page was a dream to stumble across I was able to test this in my local development settings via wamp (Windows Apache mysql php) worked great, even used JScript to develop a image tag from Google maps of the location(lat,long). A great tool for people posting comments on a site from iPhones. Thanks again for the great info and useful code :)

  16. Posted by: Let’s build a DSL « I am Zef - 01/24/2010

    [...] Location information (GPS coordinates) [...]

  17. Posted by: Cabel - 02/01/2010

    A small typo in your code: you have “altert” instead of “alert”.

    This code seems to be starting to show up in the WebKit Nightlies for Safari, but it’s incomplete, so the alert is important! :)

  18. Posted by: Doug Smith - 02/02/2010

    Good catch, Cabel. I fixed it here in the post and on my geo test page. Thanks!

  19. Posted by: Jurgen Fechner - 03/05/2010

    Excellent page to come across by accident, and the possibilities are endless :-) you could even create a trivial pursuit game for outdoor enthusiasts, when reaching a certain location, you get a cryptic clue to your next location and if you are withing a certain radius of that next location you get the next clue…etc… thanks for this page

  20. Posted by: Mark Oakden - 03/23/2010

    Thanks for this, got it working in a web app I am developing. However, my iphone seems to cache the location regardless of the maximum age value I pass. This means my app can show its last stored located for up to 10 minutes after I have switched my iphone on – unless I open google maps, in which case it refreshes the location. Anyone else experience this?

  21. Posted by: BobFix - 04/21/2010

    Great code. Tried it on my site and I was able to display Long/Lat/Alt/Speed/etc. from my iPhone and Android. Can you point me to services where I can translate this data into usable info like City/State so I can use it on my website? Also, how can my site grab this info? Thanks!

  22. Posted by: Doug Smith - 04/21/2010

    Your site could get the info. You could include it in a form field (even a hidden field) that the user submits with other form data. Or you could use AJAX to send it back to your site in real time without other user action.

    For looking up the nearest city, etc., you want what is called reverse geocoding Try Googling that term to learn more about it. Here’s a page with a few reverse geocoding links to help get you started.

  23. Posted by: erik - 04/27/2010

    hi im new into this and what im looking for is … if the user on the iphone will go to my website and my website will be able to get his location. similar to hotel search websites were then even show you the results layout on google map.

    now, i would like to give him the hotels which are near to his location and this is why i need his geo detailes.

    it means that my site should be able to grab his location and sort all the hotels in its data base base on the mobile user location

    any idea how to do that?

  24. Posted by: Doug Smith - 04/28/2010

    @erik, You can use the javascript techniques I’ve shown to populate hidden form fields. That form can have a lookup button to submit the form that would then send the hidden field lat/lon data to your server. You could then use that to do whatever database lookups you need.

  25. Posted by: Tim Stanton - 05/18/2010

    I’m not finding the javascript techniques you mention, I’m struggling to figure out how to do exactly that. being able to use Javascript data totally eludes me.

  26. Posted by: Doug Smith - 05/18/2010

    I didn’t detail out how to fill a hidden form field in my example. I just meant you could use something similar to how I printed the information on the page but instead use it within a form tag. So instead of <p>Latitude: ' + position.coords.latitude + '</p> maybe you could do something like <input type="hidden" name="latitude" value="' + position.coords.latitude + '" /> within an HTML form.

  27. Posted by: Doug Smith - 07/05/2010

    Here’s another great tutorial on geolocation in the browser: http://www.html5rocks.com/tutorials/geolocation/trip_meter/

Leave a Reply of Your Own