jQuery HTML5 地理定位实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4908370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:10:27  来源:igfitidea点击:

HTML5 Geolocation implementation

jqueryhtmlgeolocation

提问by Webnet

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?

我有一个区域和纬度/经度列表,我要求用户在访问我的网站时选择他们的位置。如果可能,我希望使用 HTML5 的地理定位预填充他们的位置,但我不确定这样做的最佳方法。网络上似乎缺乏教程,至少从我能找到的内容来看。有没有人做过这个?你知道一个好的教程/资源吗?

update

更新

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

如果我有一堆城市的坐标,我如何使用 javascript 来确定最近的位置?

回答by Horia Dragomir

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/

去这里看一个更大的演示。http://od-eon.com/labs/geolocation/

回答by Yash Kumar Verma

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.

当您想使用坐标时,只需调用 load_position() 即可。

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

注意:l是要放置数据的元素的 id。相应地修改它以满足您的需要。

回答by 1mi

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 cletusfor computing the distances.

JSfiddle链接在这里。感谢cletus计算距离。

回答by looneydoodle

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

Nettuts 有这个很棒的教程,这里是链接http://mobile.tutsplus.com/tutorials/mobile-web-apps/html5-geolocation/