【问题标题】:Get User Location with Javascript使用 Javascript 获取用户位置
【发布时间】:2019-05-18 14:04:49
【问题描述】:

我想在点击事件中获取用户当前的位置地址(城市、街道等)。

我尝试过 html5 地理定位并尝试控制数据。在按钮单击时,我通过创建警报框来检查地理位置,并且它成功执行,但它没有在控制台中打印任何值。

HTML

<div id="navbar"><span> Geolocation API</span></div>
<div id="wrapper">
<button id="location-button">Get User Location</button>
<div id="output"></div>

我的脚本

  <script>
      $('#location-button').click(function(){

        if (navigator.geolocation) {  
         alert("it is supported");
            navigator.geolocation.getCurrentPosition(function(position){
              console.log(position);
              $.get( "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ position.coords.latitude + "," + position.coords.longitude +"&sensor=false", function(data) {
                console.log(data);
              })
              var img = new Image();
              img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + position.coords.latitude + "," + position.coords.longitude + "&zoom=13&size=800x400&sensor=false";
              $('#output').html(img);
            });

        }
        else
        {
            console.log("geo location is not supported")
        }
      });
 </script>

我想获取用户位置的完整地址。

【问题讨论】:

  • 我在发布的代码中收到一个 javascript 错误:Mixed Content: The page at 'https://jsfiddle.net/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://maps.googleapis.com/maps/api/geocode/fiddle,地理定位仅适用于https:),一旦我将其更改为https:,我会得到一个“无密钥” " 静态地图请求中的错误。请注意,地理编码器请求将无法通过 javascript 工作,请使用 javacript API,请参阅:stackoverflow.com/questions/49499663/…

标签: javascript google-maps google-maps-api-3


【解决方案1】:

您可以访问此jsfiddle sample 来展示您的用例。

请注意,不建议在客户端使用 Web 服务,因为建议将 Web 服务请求用于服务器端请求。

如下所示,我使用的是Geocoder Service,而不是 Web 服务地理编码

geocoder.geocode( { 'location': pos}, function(results, status, infowindow) {
      if (status == 'OK') {
            console.log(results[0].formatted_address);
            infoWindow.setContent('Location found: '+ results[0].formatted_address);
            infoWindow.setPosition(pos);
            infoWindow.open(map);
      } else {
                console.log('Geocode was not successful for the following reason: ' + status);
      }
    });

【讨论】:

    【解决方案2】:

    你根本做不到!地理位置使用手机上的三角测量或 GPS,您将获得经度和纬度值,甚至是 IP,您将获得最近的分销商设备(英语中没有正确的词)。 显然,对于地理定位,用户也必须授权。 因此,如果您想要地址,最简单的方法就是通过表格询问。您可以使用与经度/纬度匹配相关的地图,但这样做会很痛苦和浪费,因为您必须使用地球上所有与之相关的地图和地点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 2016-06-12
      • 2020-10-21
      • 1970-01-01
      • 2012-08-19
      • 2017-10-18
      相关资源
      最近更新 更多