Google Maps JavaScript API v3距离矩阵发送lat和lng但返回地址

时间:2015-02-18 11:24:20

标签: google-maps google-maps-api-3

每一个人。

你可以看到这个链接 Google

此链接显示参数变量origin1和变量destinationB是平均值lat和lng 但我点击计算距离返回那里的地址 我想要lat和lng结果。
怎么可以?
我需要帮助。
谢谢各位朋友。

1 个答案:

答案 0 :(得分:1)

DistanceMatrixService的响应不包含LatLng。

当您查看代码时,您会看到将通过地理编码请求LatLng(用于绘制标记)。

当然你可以使用硬编码的LatLng,但结果可能不同,因为DistanceMatrixService返回的位置不能等于这些值。

如何获取LatLng,无论输入类型(地址或LatLng)如何?

地理编码以异步方式运行,无法保证结果将按特定顺序返回。因此,无法像演示一样创建字符串。

而是创建DOMNode(您要在其中显示LatLng),将这些节点作为参数传递给addMarker,并在地理编码 - 回调中将节点的内容设置为所需的值



var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];

var origin1 = new google.maps.LatLng(55.930, -3.118);
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = new google.maps.LatLng(50.087, 14.421);

var destinationIcon = 'http://www.google.com/mapfiles/dd-end.png';
var originIcon = 'http://www.google.com/mapfiles/dd-start.png';

function initialize() {
  var opts = {
    center: new google.maps.LatLng(55.53, 9.4),
    zoom: 10
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), opts);
  geocoder = new google.maps.Geocoder();
}

function calculateDistances() {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin1, origin2],
      destinations: [destinationA, destinationB],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
}

function callback(response, status) {

  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML = '';
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      //create a new "row"
      var row=outputDiv.appendChild(document.createElement('div'));
      
      var results = response.rows[i].elements;
      //origin-marker
      addMarker(origins[i], false,row.appendChild(document.createElement('code')));
      //a list for the destinations
      var list=row.appendChild(document.createElement('ul'));
      
      
      for (var j = 0; j < results.length; j++) {
        var item=list.appendChild(document.createElement('li'));
        item.appendChild(document.createTextNode(' to '));
        //destination-marker
        addMarker(destinations[j], true,item.appendChild(document.createElement('code')));
        item.appendChild(document.createTextNode([': ',
                                                  results[j].distance.text,
                                                  ' in ',
                                                  results[j].duration.text
                                                  ].join('')));

      }
    }
  }
}

function addMarker(location, isDestination,node) {
  var icon;
  if (isDestination) {
    icon = destinationIcon;
  } else {
    icon = originIcon;
  }
  geocoder.geocode({'address': location}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      bounds.extend(results[0].geometry.location);
      map.fitBounds(bounds);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        icon: icon
      });
      markersArray.push(marker);
      node.appendChild(document.createTextNode('('+marker.getPosition().toUrlValue()+')'));
      node.setAttribute('title',location);
      node.style.background=(isDestination)?'red':'green';
      google.maps.event.addDomListener(node,'click',function(){map.panTo(marker.getPosition())})
    } else {
      alert('Geocode was not successful for the following reason: '
        + status);
    }
  });
}

function deleteOverlays() {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}

google.maps.event.addDomListener(window, 'load', initialize);
&#13;
html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      #map-canvas {
        height: 100%;
        width: 50%;
      }
      #content-pane {
        float:right;
        width:48%;
        padding-left: 2%;
      }

      #outputDiv>div:nth-child(n+2){
         border-top:1px dotted silver;
      }
      #outputDiv code{
        cursor:pointer;
        color:#fff;
      }
&#13;
<script src="https://maps.googleapis.com/maps/api/js?v=3&.js"></script>
    <div id="content-pane">
      <button type="button" onclick="calculateDistances();">
        Calculate distances
      </button>
      <div id="outputDiv"></div>
    </div>
    <div id="map-canvas"></div>
&#13;
&#13;
&#13;