Map Scripting

Icon

Create Location-based Web Applications

How to Use iPhone JavaScript Geolocation

Update: iPhone OS 3.0 is now out. I have updated the code below to the latest geolocation spec, which the iPhone supports.


There will soon be a new iPhone and a third version of the phone’s operating system. Among the new features in iPhone OS 3.0 is geolocation in the web browser, which will be available on all iPhones–not just the new one. As a developer who appreciates the single platform of the web, this is the most exciting news.

I’ve had a number of people suggest that I should create an iPhone app for my Portland WiFi finder site. While I like the idea of being able to immediately show closest hotspots, it seems like a lot of work for a small number of users (sorry Portland laptoperati).

Plus, I love the web. It is my favorite platform. Geolocation in a simple browser is becoming more common, though it usually involves installing an add-on. I expect that will change, with browsers incorporating geolocation just as Apple has with the iPhone. The Opera browser has already done this and Firefox’s next version will, too.

There is even a W3C standard for geolocation being developed. From the looks of Apple’s documentation, the iPhone supports the specification, which adds a navigator.geolocation object.

You can try it out on your iPhone by going to this shortened URL:
http://bit.ly/w3cgeo

Here’s code for finding the location of your user in the iPhone 3.0 version of Safari:

navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

function foundLocation(position)
{
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  alert('Found location: ' + lat + ', ' + long);
}
function noLocation()
{
  alert('Could not find location');
}

The getCurrentPosition function requires two arguments, which are each function references. You can write them as inline, anonymous functions, or name them as I have above.

Upon success, the first function will be called. As you can see, an object containing the latitude and longitude is passed to this function. My code just echos the data in an alert, but yours will likely center a map or lookup nearby locations.

As with any geolocation, the user will have to give permission to provide the location data. If they deny, or if there is an error, the second function is called. Use this function to perform any tasks necessary for a non-geolocated user. I send a message through an alert, but you probably won’t want to do this.

Native geolocation on the iPhone should get the feature more respect and pick-up in all browsers. Hopefully Google Gears, which also provides this feature to browsers and mobile phones, will adopt the W3C spec so that we have one, standard way to access geo data.

Category: How-tos

Tagged:

46 Responses

  1. [...] Adam DuVander (the fellow behind the Portland Wifi Finder among other things) has written up an excellent post on how to access their location. The iPhone is using the W3C Geo-Location spec. If you are running [...]

  2. [...] How to Use Geolocation in Mobile Safari – Map Scripting iPhone OS 3.0 is now out. I have updated the code below to the latest geolocation spec, which the iPhone supports. (tags: content tutorial geolocation iphone) [...]

  3. [...] Adam DuVander (the fellow behind the Portland Wifi Finder among other things) has written up an excellent post on how to access their location. The iPhone is using the W3C Geo-Location spec. If you are running [...]

  4. [...] How to Use Geolocation in Mobile Safari – Map Scripting [...]

  5. [...] explained iPhone geolocation in a post on my book [...]

  6. Jay Crossler says:

    I love this stuff! I just posted a post with more details and a bunch of code examples on how to do GeoLocation and Offline Web Databases at: http://wecreategames.com/blog/?p=210

    I think this is really a game-changer and will evolve how applications are developed — much more HTML-based, and less native apps.

  7. [...] itself simple JavaScript Google Maps API, that uses two cunning tricks: this Clustering code, and this code that uses the new nascent W3C geolocation standard that the iPhone3 supports, like [...]

  8. [...] itself simple JavaScript Google Maps API, that uses two cunning tricks: this Clustering code, and this code that uses the new nascent W3C geolocation standard that the iPhone3 supports, like [...]

  9. [...] How to Use Geolocation in Mobile Safari – Map Scripting (tags: safari mobile geo location javascript geocoding) [...]

  10. With geolocation tools like this now baked into the browser, replicating the native iPhone Maps app is child’s play: http://plebeosaur.us/you-are-here-with-safari-on-iphone/

    Expect a flood of location-aware web innovation in the next year.

  11. Mike P. says:

    Thanks Adam – this is just what I needed!

  12. omarius says:

    Realy Nice !

    Is there a painless method to get a Countryname or countrycode from the gps data?

  13. AdamD says:

    Omarius,

    There are several JavaScript-based IP geolocators. That’s the route I’d take, because it will work for almost all of your visitors. The easiest comes in Google’s Ajax Loader, which would be convenient because you can use it to load Google Maps, too (assuming you use it).

    More about it here:
    http://code.google.com/apis/ajax/documentation/#ClientLocation

  14. Pasha says:

    Thats great, but…as we all know from using an iPhone experience, the user’s location accuracy is not great from the initial request to get a location. When using google maps it takes about 30 seconds to turn on GPS and find a location with hight level of accuracy.

    Thats why I think it would be much more useful to use navigator.geolocation.watchPosition.

    What would be great to see is some code example where it tries to find a best possible accuracy within say 30 seconds.

  15. russell says:

    excellent! i’ve been looking for something like this. thanks for the info.

  16. [...] should make you feel good about mobile web standards. Mapping pioneer MapQuest is now using the geolocation standard to provide directions from your current location in MapQuest Mobile — m.mapquest.com, which [...]

  17. [...] some googling I found a hint from Adam to get the geo position directly via javascript if the browser is running on a mobile device. The [...]

  18. [...] addition to the W3C geolocation standard (I covered iPhone geolocation previously) and finding your user’s location based on IP, there are a number of services that [...]

  19. [...] been a year since iPhone added geolocation to its browser. It’s also now available in Android and in many desktop browsers. The standard [...]

  20. [...] I’ve written previously iPhone geolocation using JavaScript is quite easy. In addition to grabbing the location once, you can use the W3C geolocation standard [...]

  21. scott says:

    dictatorial@hettys.rejects” rel=”nofollow”>.…

    good info!…

  22. Armando says:

    lewisohn@dora.progandist” rel=”nofollow”>.…

    спс….

  23. Jay says:

    mckinley@tillie.appalled” rel=”nofollow”>.…

    ñïñ!!…

  24. brad says:

    granules@pertinence.burn” rel=”nofollow”>.…

    good!…

  25. jackie says:

    craftsmans@chutney.traps” rel=”nofollow”>.…

    ñïñ!…

  26. Herbert says:

    tam@spider.voroshilov” rel=”nofollow”>.…

    thanks….

  27. gregory says:

    repeats@liberality.esterases” rel=”nofollow”>.…

    ñýíêñ çà èíôó….

  28. timothy says:

    midwest@married.modish” rel=”nofollow”>.…

    hello….

  29. ian says:

    firm@sofas.estimate” rel=”nofollow”>.…

    ñïñ çà èíôó!!…

  30. Andrew says:

    invalidate@concurrently.locating” rel=”nofollow”>.…

    ñïñ….

  31. Donnie says:

    squabbling@delegate.complainant” rel=”nofollow”>.…

    áëàãîäàðþ….

  32. luis says:

    beans@zoologist.casters” rel=”nofollow”>.…

    ñïñ!…

  33. jeff says:

    skill@reasonable.dutton” rel=”nofollow”>.…

    tnx for info!…

  34. bernard says:

    circumscribed@pikes.rides” rel=”nofollow”>.…

    thanks!!…

  35. harold says:

    grows@felt.cubists” rel=”nofollow”>.…

    ñïñ!!…

  36. stephen says:

    imperiously@larsons.millidegree” rel=”nofollow”>.…

    ñïàñèáî çà èíôó!…

  37. Daryl says:

    haystacks@braids.bahia” rel=”nofollow”>.…

    thanks for information!!…

  38. todd says:

    exert@thermos.serratus” rel=”nofollow”>.…

    tnx….

  39. Jonathan says:

    insofar@rundfunk.nicotine” rel=”nofollow”>.…

    hello!…

  40. Mitchell says:

    seeded@stannard.alien” rel=”nofollow”>.…

    ñýíêñ çà èíôó!!…

  41. Casey says:

    tease@steve.quietism” rel=”nofollow”>.…

    спасибо за инфу!…

  42. Luis says:

    recessed@maitre.juggling” rel=”nofollow”>.…

    сэнкс за инфу!!…

  43. Alberto says:

    blowing@daughters.shrunken” rel=”nofollow”>.…

    спс за инфу….

  44. Shannon says:

    definable@greatest.bloomfield” rel=”nofollow”>.…

    tnx!!…

  45. Evan says:

    depression@protuberance.translations” rel=”nofollow”>.…

    спасибо за инфу!!…

Leave a Reply

Adam DuVanderHi, I'm Adam. I'm writing a book about developing maps on the web. This site is where I'll share the things I find and help you create your own maps. Find out more.

Map Scripting 101