搜索地址与Google Maps api v3上最近的现有地标之间的距离

时间:2012-05-30 20:50:44

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

我正在开发一个包含Google Maps API v3的网页。我目前有一个功能图和搜索栏。我需要能够在地图上的某个KML文件上显示搜索地址到最近地标的距离。我怎么能这样做?

以下是该页面的代码:

<script type="text/javascript">
    var geocoder;
    var map; 
    var marker;
    var layers = [];
  function initialize() {
    geocoder = new google.maps.Geocoder ();
    var latlng = new google.maps.LatLng (41, -73.4);
    var myOptions = {
      zoom: 7,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
        }
      map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
      marker = new google.maps.Marker({map:map});


        layers[0] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/South-and-North-County-Trailway.kml',
            {preserveViewport: true});
        layers[1] = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml', 
            {preserveViewport: true});
        layers[2] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NWS%20Radar%20Images.kmz', 
            {preserveViewport: true});
    for (var i = 0; i < layers.length; i++) {
                layers[i].setMap(map);
              }
        }

    function codeAddress () {
        var address = document.getElementById ("address").value;
        geocoder.geocode ( { 'address': address}, function(results, status)  {
        if (status == google.maps.GeocoderStatus.OK)  {
            map.setCenter(results [0].geometry.location);
            marker.setPosition(results [0].geometry.location);
            map.setZoom(14);
            } 
        else {
            alert("Geocode was not successful for the following reason: " + status);
                }
        }); 
                            }
    function toggleLayer(i) {
      if(layers[i].getMap() === null) {
        layers[i].setMap(map);
      }
      else {
        layers[i].setMap(null);}
    }

</script>

1 个答案:

答案 0 :(得分:1)

您无法访问KML图层中的数据

https://developers.google.com/maps/documentation/javascript/layers#KMLLayers

  

由于KML可能包含大量功能,因此您可能无法访问   直接从KmlLayer对象获取要素数据。相反,作为功能   如果显示,它们将呈现为可点击的Maps API   叠加层。

相反,您可以处理XML并手动添加标记,然后使用geometry librarycomputeDistanceBetween()来获取距离。我通常将距离乘以某个数来考虑转弯(距离公式得到直线距离)。我认为1.2周围最准确。