4

我正在使用 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>
4

1 回答 1

1

您不能像那样访问 KML 图层中的数据

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

由于 KML 可能包含大量要素,因此您可能无法直接从 KmlLayer 对象访问要素数据。相反,在显示要素时,它们会呈现为看起来像可点击的 Maps API 叠加层。

相反,您可以手动处理 XML 并添加标记,然后使用几何库computeDistanceBetween()获取距离。我通常将距离乘以某个数字来计算转弯(距离公式得到直线距离)。我相信周围1.2是最准确的。

于 2012-05-30T21:08:27.350 回答