get current latitude and longitude from gps enabled device

44,055

Solution 1

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.

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

Many thanks to Mark Pilgrim for his awesome post.

Solution 2

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");
Share:
44,055
davidlee
Author by

davidlee

Updated on January 04, 2021

Comments

  • davidlee
    davidlee over 3 years

    I would like to get the latitude and longitude of current location from gps enabled mobile device right from the web browser. May I know is this possible? how to do it? does it require geolocation api? Some coding example would be helpful. Thanks.

  • davidlee
    davidlee over 13 years
    is it means that html5 geolocation api can be used by all gps enabled devices? thanks..
  • David Mårtensson
    David Mårtensson over 12 years
    Mark Pilgrim's post you link to is no longer available :(
  • Buhake Sindi
    Buhake Sindi over 11 years
    Google Gears is long deprecated.
  • Marko
    Marko over 11 years
    @BuhakeSindi this was answered 2.5 years ago.
  • SimonM
    SimonM over 7 years
    This does not work on mobile networks or Chrome (only https) or Safari. I use ipinfo.io which is ok for wifi connected devices but returns lat long of networks ISP.