With the iPhone 3.0 firmware released today, I thought I’d show you how to access one of the features I’ve been most looking forward to – support for the geolocation API in Safari means I can now create location aware websites.

This will be just a quick demo to retrieve and display the current longitue and latitude of your phone, along with a googlemap so we can see if the results are right.  The more interesting applications will come….

To do this we’ll use javascript and the newly added Navigator.Geolocation interface to call the getCurrentPosition() function to retrieve the current longitude and latitude of the phone, which we’ll display and pass to the googlemaps API.

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>iPhone 3.0 geolocation demo</title>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport"/>
<script>
function handler(location) {
var message = document.getElementById("message");
message.innerHTML ="<img src='http://maps.google.com/staticmap?center=" + location.coords.latitude + "," + location.coords.longitude + "&size=300x200&maptype=hybrid&zoom=16&key=YOURGOOGLEAPIKEY' />";
message.innerHTML+="<p>Longitude: " + location.coords.longitude + "</p>";
message.innerHTML+="<p>Latitude: " + location.coords.latitude + "</p>";
message.innerHTML+="<p>Accuracy: " + location.coords.accuracy + "</p>";
}
navigator.geolocation.getCurrentPosition(handler);
</script>
</head>
<body>
<div id="message">Location unknown</div>
</body>
</html>

The results:

Try it for yourself by pointing your Safari browser at http://bemoko.com/blog/iphonegeo.

Update 27/7/2009: I noticed the zoom level on the google static map API wasn’t being set so the map was zoomed all the way out. I’ve added a default zoom for the demo code above. Not sure if thats a new requirement from Google’s side?

Posted in: mobile web

Related articles

22 Responses to “iPhone 3.0 geolocation javascript API”

  1. Greg says:

    Can you post the demo online so people can try it?

  2. H@nnes says:

    Pretty cool, did not realize until now! Now what’s missing is a way to determine which SDK is installed. Any idea? Thanks!

  3. Stanislav says:

    @H@annes

    This looks like simple:
    if(typeof(navigator.geolocation) != “undefined” && typeof(navigator.geolocation.getCurrentPosition) != “undefined”) {
    /* iPhone OS3 */
    }

  4. Justin says:

    @Stanislav
    All that tells you is that the current user agent supports the W3C’s geolocation API (http://dev.w3.org/geo/api/spec-source.html). It doesn’t tell you if the user agent is safari or iPhone 3.0. For instance, that test passes in Firefox 3.5.

  5. [...] We’re already seeing a taster of this HTML5 support, with the iPhone geolocation support in iPhone 3.0. Many apps currently in the app store realm lend themselves well to a personalised microsite with [...]

  6. Nelson says:

    Thanks for the demo code! I cribbed off it to make a little webapp that shows nearby Wikipedia articles. More details on my blog at http://www.somebits.com/weblog/tech/wikihere.html

  7. Mike says:

    So with a xml document that only stores the names of cities eg: New York, Boston, London, Sydney etc. What would be the simplest way to interface the long and lat data with the city name strings.

    Does a database of city long and lats exist that i could reference with javascript?

  8. Daniel says:

    Mike: try to use Googlemaps API -> Google knows what u want ;) they really do!

  9. [...] – Determine user location. On iPhone this means limited access to the GSP/Location API. This example demonstrates how easy it is to ask Safari for the user’s [...]

  10. Just did a head to head with my iPhoneGS versus my Droid.

    Even with position options set to {enableHighAccuracy:true, maximumAge: 0}. The I phone just stunk.

    Looks like it was giving me the Address of the cell tower. If I left Safari, and did a GetLocation from Google Mapples.

    The next calls from within Safari got the correct location. This really needs to be fixed.

    Droid rocked it out. I was able to walk through the park, updating my GeoCode every 30, through JavaScript on the browser.

  11. Found this entry today, definitely some changes to the result set. The problem was that my iPhone took too long to get it’s location, after a few requests. It was able to ‘lock’ in on me. In fact, during intensive tests 3 weeks ago the iPhone outperformed Droid on the GPS.

    Very happy with both platforms and the possibilities.

  12. Chi Patts says:

    Hello, I came across this article while searching for help with JavaScript. I have recently switched browsers from Google Chrome to Firefox 3.2. After the change I seem to have a problem with loading JavaScript. Every time I go on a website that needs Javascript, the site does not load and I get a “runtime error javascript.JSException: Unknown name”. I cannot seem to find out how to fix the problem. Any help is very appreciated! Thanks

  13. Asakura says:

    Found this entry today, definitely some changes to the result set. The problem was that my iPhone took too long to get it&#30;s location, after a few requests. It was able to 'lock' in on me. In fact, during intensive tests 3 weeks ago the iPhone outperformed Droid on the GPS.

    Very happy with both platforms and the possibilities.;

  14. Craig says:

    Hopefully the writer is reading this comment. Any info on OS4 Beta? It seems this code does not work. I went to your test site and it returned ‘Location Unknown’

  15. Ian Homer says:

    Thanks for the heads up. We’ll give it a go on OS4

  16. Nic says:

    That is beautiful.

    I have been looking for this functionality for many months now, and I have been told by a number of people (who should know better) that its not possible to get someones phone location from their browser.

    Great post

    Nic

  17. Ivan says:

    @Craig: It seems that Apple has decided to modify their support. I’ve found that the GPS data provided using the Web-based API may correspond only to the AGPS (Assisted location) which lacks accuracy. Hopefully, they will release something soon to fix or inform about how to get more accurate data using the API.

  18. Umut Aydin says:

    Hello,

    I couldn’t run it on iPhone 4 Simulator. I try to show an alert box with position data. There is no error but no result also.
    Any known problem like that?

Leave a Reply