【问题标题】:GeoLocation Zip Code地理位置邮政编码
【发布时间】:2011-05-17 15:50:03
【问题描述】:

我正在使用以下代码获取位置和城市,但如果该人允许我,我无法获得它来给我邮政编码。请让我知道这是否可能与此代码有关。如果获得访问权限,它所做的只是填充一个文本字段。

<script type="text/javascript">
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
     $("#location").val(position.address.city+", "+position.address.region);
  });
 }

【问题讨论】:

    标签: javascript html geolocation


    【解决方案1】:

    试试position.address.postalCode

    查看我制作的以下演示,了解您的浏览器/设备支持什么

    https://jsfiddle.net/gaby/Sx5cj/

    【讨论】:

    • (index):78 [Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS 在控制台中。
    • @Azimuth 只需使用 https:// 版本的 jsfiddle。也更新了答案。
    • 在 Chrome 中不起作用。 position.address 未定义。
    【解决方案2】:

    查看最新的HTML5 Geolocation API,我还没有看到对position.address.cityposition.address.regionposition.address.city 的支持。所以,我不得不说目前不支持。


    更新:

    根据@Gaby aka G. Petrioli 的回答,Firefox 似乎支持地址查找

    【讨论】:

      【解决方案3】:

      HTML 5 Geolocation API 中不支持地址,但您可以将其与 Google Maps API 结合使用: 这是一个获取邮政编码的示例,但您可以使用它来获取整个地址:

      if(navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
              var lat = position.coords.latitude;
              var long = position.coords.longitude;
              var point = new google.maps.LatLng(lat, long);
              new google.maps.Geocoder().geocode(
                  {'latLng': point},
                  function (res, status) {
                      var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
                      $("#location").val(zip);          
                  }
              );
          });
      }
      

      【讨论】:

      • $("#location").val(zip);应该是 $("#location").val(zip[1]);否则它将返回整个数组的内容。
      • 不错的主意,但是现代浏览器中内置了 google api 吗?
      • @KevinDanikowski 不,您将 google maps api 作为 CDN
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多