get current latitude and longitude from gps enabled device

Use the HTML5 Geolocation API, here's the official spec and examples.

EDIT

I've updated my answer to include current browser support.

W3C Geolocation API support

Firefox 3.5+
Safari 5.0+
Chrome 5.0+
Opera
iPhone 3.0+
Android 2.0+

· ·
Other phones not listed above use Gears or their own, platform-specific APIs.

  • W3C geolocation API
  • Gears
  • BlackBerry geolocation API
  • Nokia geolocation API
  • Palm geolocation API
  • OMTP BONDI geolocation API

Ahh, will we ever have just one single API? :)

Many thanks to Mark Pilgrim for his awesome post.


Here is an actual JavaScript code which uses HTML5 Geolocation API. The following works on both Android browser and iPhone Safari:

            function onPositionUpdate(position)
            {
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                alert("Current position: " + lat + " " + lng);
            }

            if(navigator.geolocation)
                navigator.geolocation.getCurrentPosition(onPositionUpdate);
            else
                alert("navigator.geolocation is not available");