8

I have a list of areas and lattitude/longitude which I'm asking the user to select their location when they hit my site. I'd like to have their location prefilled using HTML5's geolocation if possible, but I'm not exactly sure the best way to do that. There seems to be a lack of tutorials on the web, at least from what I can find. Has anyone done this? Do you know of a good tutorial/resource?

update

If I have coordinates of bunch of cities, how can I use javascript to determine the closest location?

Ben
  • 60,438
  • 111
  • 314
  • 488
  • 1
    The W3C Geolocation API isn't part of the HTML5 spec, fwiw. (See: http://isgeolocationpartofhtml5.com/) – npdoty Feb 05 '11 at 21:50
  • Well, this can be done simply by calculating the distance between the coordinates. Use the formula `square_root((x1^2 - x2^2) + (y1^2 - y2^2))` Where the two coordinates are `(x1,y1)` and `(x2,y2)` – Yash Kumar Verma Apr 08 '16 at 11:59

4 Answers4

9

Try this example:

window.onload = function(){
    if(navigator.geolocation)
        navigator.geolocation.getCurrentPosition(handleGetCurrentPosition, onError);
}

function handleGetCurrentPosition(location){

    location.coords.latitude;
    location.coords.longitude;
}
function onError(){...}

Go here for a larger demo. http://od-eon.com/labs/geolocation/

Horia Dragomir
  • 2,858
  • 24
  • 21
0
function load_position() 
{
    if (navigator.geolocation) 
        {
            navigator.geolocation.getCurrentPosition(showPosition);
        } 
    else 
        { 
            l.innerHTML = "Geolocation is not supported by this browser.";
        }
}
function showPosition(position) 
    {
        l.innerHTML = "Longitude" +  position.coords.latitude + " Longitude " + position.coords.longitude + "</td></tr>" ;  
    }

Just make a call to load_position() when you want to use coordinates.

note: l is the id of the element in which data is to be put. Modify it accordingly to suit your needs.

Yash Kumar Verma
  • 9,427
  • 2
  • 17
  • 28
  • how come the position object is passed to the showPosition method as an argument without explicitly stating so? – Igor L. Jun 05 '17 at 18:41
0

To obtain your location AND the city closest to you from a list, you can try this:

<!DOCTYPE html>
<html>
<head>
    <title>findClosest</title>
</head>
<body>
    <button id='find-btn'>Find closest city</button>
    <br />
    <div id='out'></div>
    <select id='cities'>
        <option selected></option>
        <option value='35.6,139.6'>Tokyo</option>
        <option value='52.5,13.3'>Berlin</option>
        <option value='-33.8,151.2'>Sydney</option>
        <option value='40.2,-47'>New York City</option>
    </select>
    <script>
        var cities = document.getElementById('cities').children;
        // convert to radians
        function deg2rad(val) {
            return val * Math.PI / 180.0;
        }
        // compute distance in kilometers: https://stackoverflow.com/a/365853/6608706
        function distance(lat1, lon1, lat2, lon2) {
            var earthRadiusKm = 6371, //km
                dLat = deg2rad(lat2 - lat1),
                dLon = deg2rad(lon2 - lon1);
            lat1 = deg2rad(lat1);
            lat2 = deg2rad(lat2);
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            return earthRadiusKm * c; //km
        }
        // gets index of closest city
        function findClosest(lat, lon) {
            var idx = 1,
                dist = 50000,
                tdist,
                latlon, i;
            for (i = 1; i < cities.length; i++) {
                latlon = cities[i].value.split(',')
                tdist = distance(lat, lon, +latlon[0], +latlon[1]);
                if (tdist < dist) {
                    dist = tdist;
                    idx = i;
                }
            }
            return idx;
        }
        // find our position
        function findMe() {
            var out = document.getElementById('out');
            if (!navigator.geolocation) {
                out.innerHTML = '<p>Geolocation is not supported by your browser</p>';
                return;
            }

            function success(position) {
                var c = position.coords;
                var keys = Object.keys(position);
                var idx = findClosest(c.longitude, c.latitude);
                out.innerHTML = '<p>You are at longitude=' + c.longitude + ', latitude=' + c.latitude +
                    '<br/><br/>You are closest to: </p>';
                cities[0].selected = false;
                cities[idx].selected = true;
            }

            function error() {
                out.innerHTML = 'Unable to retrieve your location';
            }
            out.innerHTML = '<p>Locating…</p>';
            navigator.geolocation.getCurrentPosition(success, error);
        }

        document.getElementById('find-btn').addEventListener('click', findMe);
    </script>
</body>
</html>

JSfiddle link is here. Credits to cletus for computing the distances.

1mi
  • 121
  • 1
  • 4
-1

There is this awesome tutorial at Nettuts, here is the link http://mobile.tutsplus.com/tutorials/mobile-web-apps/html5-geolocation/

looneydoodle
  • 369
  • 6
  • 26