4

我一直在浏览文档和网络上的一个例子,但我找不到这个用例的例子。

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

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

4

2 回答 2

3

You can pass any text as the address key for the geocoder. If the geocoding is successsful, you should get an array of results.

From then on you can pick the first result or iterate over the array. Each of its elements should contain an address object, and postal code is one posible field on that obj.

Keep in mind that usps zipcodes are not points nor shapes. They are arrays of points, and the centroid of the polygon drawn by using those points as vertexes probably doesn't have any special meaning.

于 2013-09-24T00:45:44.183 回答
0

也许您可以使用以下脚本通过 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'
  });
}

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

于 2014-10-28T13:54:42.117 回答