【问题标题】:Convert zip code to latitude/longitude coordinates using Google Maps API?使用 Google Maps API 将邮政编码转换为纬度/经度坐标?
【发布时间】:2013-09-29 01:09:12
【问题描述】:

我一直在浏览文档和整个网络以查找此示例,但找不到此用例的示例。

给定一个邮政编码,我需要以纬度/经度坐标的形式粗略估计用户的位置。我只有邮政编码,没有别的。

这可以使用 Google Maps API 完成吗?如果没有,您还建议查看哪些其他资源?

【问题讨论】:

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


【解决方案1】:

也许你可以通过 php 使用以下脚本来做到这一点:

function getLnt($zip){
  $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";

  $result_string = file_get_contents($url);
  $result = json_decode($result_string, true);

  $result1[]=$result['results'][0];
  $result2[]=$result1[0]['geometry'];
  $result3[]=$result2[0]['location'];
  return $result3[0];
}

如果你调用这个函数(*我过滤掉了字符之间的空格,没有必要):

 $coords = str_replace(' ','',$foo->zipcode);*
 $val = getLnt($coords);

 /* print latitude & longitude for example */
 print $val['lat'];
 print $val['lng'];

然后你可以将它与你的谷歌地图脚本混合,比如:

function initialize(){
  var myLatlng = new google.maps.LatLng(<?= $val['lat'] ?>,<?= $val['lng'] ?>);
  var mapOptions = {
    zoom: 14,
    center: myLatlng,
    disableDefaultUI: true,
    scrollwheel: false,
  }
  var map = new google.maps.Map(document.getElementById('propMap'), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'title of location',
      icon: iconBase + 'google-marker.png'
  });
}

注意:这对我来说效果很好,但也许有更好的方法来做到这一点;-)

【讨论】:

    【解决方案2】:

    您可以传递任何文本作为地理编码器的地址键。如果地理编码成功,您应该得到一个结果数组。

    从那时起,您可以选择第一个结果或遍历数组。它的每个元素都应该包含一个地址对象,而邮政编码是该 obj 上的一个可能字段。

    请记住,usps 邮政编码既不是点也不是形状。它们是点的数组,以这些点为顶点绘制的多边形的质心可能没有任何特殊含义。

    【讨论】:

      猜你喜欢
      • 2015-03-02
      • 2012-10-30
      • 2013-02-23
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 2020-02-23
      相关资源
      最近更新 更多