开发者

HTML5 Geolocation implementation

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开发者_StackOverflow中文版 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?


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/


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜