如何在不征得许可的情况下获取用户的位置,或者如果用户允许一次,那么不需要再次询问?

12 javascript php latitude-longitude

我正在使用MySQL,JavaScript和Ajax创建一个门户网站,我希望在纬度和经度方面获取用户的位置.如果在没有询问的情况下无法获取位置,那么一旦用户授予权限,我可以从任何页面获取位置而无需再次询问.

提前致谢.

Séb*_*ien 18

在这个答案中有3种方法:

  1. 获取GPS精确位置,要求用户允许访问其浏览器的API
  2. 使用外部GeoIP服务获取大致位置(国家,城市,地区)
  3. 使用CDN服务获取大致位置(国家,城市,地区)

要求用户允许访问其浏览器的API

您可以使用HTML5功能获取客户端的位置.如果用户具有GPS或大致位置,则可以获得用户的确切位置.一旦用户批准分享他的位置,您将获得它,而无需更多批准.此解决方案使用Geolocation.getCurrentPosition().大多数情况下,需要在HTTPS协议下执行此操作.

如果你赶时间,这是一个CodePen与这个解决方案:https://codepen.io/sebastienfi/pen/pqNxEa

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to get your coordinates:</p>

<button onclick="getLocation()">Try It</button>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            // Success function
            showPosition, 
            // Error function
            null, 
            // Options. See MDN for details.
            {
               enableHighAccuracy: true,
               timeout: 5000,
               maximumAge: 0
            });
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;  
}
</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

处理错误和拒绝 getCurrentPosition()方法的第二个参数用于处理错误.如果无法获取用户的位置,它指定要运行的函数:

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

在地图中显示结果

function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;

    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=
    "+latlon+"&zoom=14&size=400x300&sensor=false";

    document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
Run Code Online (Sandbox Code Playgroud)

GeoIP的

如果上述解决方案在您的方案中不起作用,您可以使用IP的位置获取大致位置.您不一定会获得用户的确切位置,但可能最终得到用户连接点区域中最近的Internet节点的位置,这可能足够接近99%的用例(国家,城市,区域) .

由于这不精确但不需要用户的批准,这也可能符合您的要求.

找到以下2种方法.我建议使用CDN解决方案,因为它更快,是的,速度很重要.

使用外部GeoIP服务获取大致位置(国家,城市,地区)

许多外部服务允许您获取GeoIP位置.以下是Google的一个示例.

要获取Google API密钥,请访问:https://developers.google.com/loader/signup?csw = 1

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Get web visitor's location</title>
        <meta name="robots" value="none" />
    </head>
    <body>
    <div id="yourinfo"></div>
    <script type="text/javascript" src="http://www.google.com/jsapi?key=<YOUR_GOOGLE_API_KEY>"></script>
    <script type="text/javascript">
        if(google.loader.ClientLocation)
        {
            visitor_lat = google.loader.ClientLocation.latitude;
            visitor_lon = google.loader.ClientLocation.longitude;
            visitor_city = google.loader.ClientLocation.address.city;
            visitor_region = google.loader.ClientLocation.address.region;
            visitor_country = google.loader.ClientLocation.address.country;
            visitor_countrycode = google.loader.ClientLocation.address.country_code;
            document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
        }
        else
        {
            document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
        }
    </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

使用CDN服务获取大致位置(国家,城市,地区)

大多数CDN都提供了使用外部服务的替代方案.此解决方案的优点是不需要额外的HTTP请求,因此速度更快.如果您已经拥有CDN,那么这就是您的选择.您可以使用CloudFlare,CloudFront等.

在这种情况下,您很可能最终将该位置作为HTTP请求标头的参数,甚至直接在窗口对象中,以便您可以使用Javascript获取它.阅读CDN的文档以了解更多信息.

2018年12月中旬编辑,增加了更多选择.

  • 可以肯定的是,Google API 不再返回这些对象属性。至少在我的测试中,它在 2019 年 2 月 14 日有效。 (2认同)

Kur*_*den 10

您可以使用https://www.geoip-db.com等外部服务.它们提供基于IP地址的地理定位服务,您无需用户权限.

试试这个例子:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Geo City Locator</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body> 
    <div>Country: <span id="country"></span></div>
    <div>State: <span id="state"></span></div>
    <div>City: <span id="city"></span></div>
    <div>Latitude: <span id="latitude"></span></div>
    <div>Longitude: <span id="longitude"></span></div>
    <div>IP: <span id="ip"></span></div>
    <script>
      $.getJSON('https://geoip-db.com/json/')
         .done (function(location) {
            $('#country').html(location.country_name);
            $('#state').html(location.state);
            $('#city').html(location.city);
            $('#latitude').html(location.latitude);
            $('#longitude').html(location.longitude);
            $('#ip').html(location.IPv4);
         });
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)