我如何在不寻求许可的情况下获得用户的位置,或者如果用户一次获得许可,则无需再次询问? [英] How can I get user's location without asking for the permission or if user permitted once so need not to ask ever again?

查看:29
本文介绍了我如何在不寻求许可的情况下获得用户的位置,或者如果用户一次获得许可,则无需再次询问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MySQL,JavaScript和Ajax创建门户,我想获取经纬度方面的用户位置.如果无法不询问就无法获取位置,那么一旦用户授予许可,我就可以从任何页面获取位置而无需再次询问.

I am creating a portal using MySQL, JavaScript and Ajax and I want to fetch user's location in terms of latitude and longitude. if it is not possible to fetch the location without asking then once user grant the permission, I could fetch the location from any page without asking ever again.

预先感谢.

推荐答案

在此答案中执行此操作的3种方法:

3 ways to do this in this answer:

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


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

您可以使用HTML5功能获取客户端的位置.如果它是通过具有GPS的设备或近似位置完成的,则将为您提供用户的确切位置.一旦用户批准分享他的位置,您将无需任何其他批准即可获得它.此解决方案使用 Geolocation.getCurrentPosition().在大多数情况下,必须在HTTPS协议下执行此操作.


Ask the user to allow access to its browser's API

You can get the location of the client using HTML5 features. This will get you the exact location of the user if it is done from a device which has a GPS, or an approximate location. Once the user approved to share his location, you'll get it without any more approval. This solution uses Geolocation.getCurrentPosition(). It is required for most cases to do this under HTTPS protocol.

如果您着急的话,这里是使用此解决方案的CodePen: https://codepen.io/sebastienfi/pen/pqNxEa

If you are in a hurry, here is a CodePen with this solution: 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>

处理错误和拒绝getCurrentPosition()方法的第二个参数用于处理错误.它指定了在无法获取用户位置时要运行的功能:

Handling Errors and Rejections The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

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;
    }
}

在地图中显示结果

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+"'>";
}

GeoIP

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

GeoIP

If the solution above doesn't work in your scenario, you can obtain an approximate position using IP's location. You will not necessarily get the exact location of the user, but may end up with the location of the nearest Internet node in the user's connection point area, which may be close enough for 99% of the use cases (country, city, area).

由于这并不精确,但不需要用户的批准,因此这也可能满足您的要求.

As this is not precise but doesn't require the user's approval, this may also meet your requirements.

找到以下两种方法来做到这一点.我建议您使用CDN解决方案进行此操作,因为它速度更快,是的,速度很重要.

Find below 2 ways to do that. I would recommend doing this using the CDN solution because it is faster and yes, speed matters a lot.

许多外部服务使您可以获取GeoIP位置.这是Google的示例.

Many external services allows you to obtain the GeoIP location. Here is an example with Google.

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

To get your Google API Key, go here: 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>

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

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

Get an approximate location (country, city, area) using CDN service

An alternative to using external services is provided by most of the CDN. The advantage of this solution is that no extra HTTP request is required, so it is faster. If you already have a CDN, this is the way to go. You can use CloudFlare, CloudFront, etc.

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

In this scenario, you will most likely end up with the location as a parameter of the HTTP request's header, or even directly in the window object so you can get it with Javascript. Read the CDN's documentation to know more.

于2018年12月中旬编辑以添加更多选项.

Edited on mid December 2018 to add more options.

这篇关于我如何在不寻求许可的情况下获得用户的位置,或者如果用户一次获得许可,则无需再次询问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆