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">
		<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 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>');  
		<div id="geoinfo"></div>

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 thoughts on “GPS Geolocation in Safari on iPhone OS 3.0”

  1. Hi,
    I work for the website . 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?

    1. 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.

  2. 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?

    1. @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?

  3. @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.

    1. @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.

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



  5. 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.


  6. 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?

  7. 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 🙂

  8. 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! 🙂

  9. 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

  10. 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?

  11. 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!

    1. 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.

  12. 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?

    1. @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.

  13. 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.

    1. 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.

Leave a Reply