谷歌地图不会在地图上显示所有目标标记,只显示第一个和最后一个

时间:2016-03-22 08:10:44

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

我有一张谷歌地图,可以正确显示所有标记的路线。 https://jsfiddle.net/az5tk8ns/17/

目的地是硬编码的: destinations = ["", "durban,KZN", " ixpop,kzn"]

然后我有另一个函数产生我的地址数组:

var addresses = [];
addresses.push('Durban, KZN');
addresses.push('izopo, KZN');`

然后我设置:

destinations = addresses

https://jsfiddle.net/az5tk8ns/19/

执行此操作时,地图仅显示开始和结束目标标记,而不是我在中间停止?

我如何使用此方法,以便将动态生成的地址数组传递给谷歌地图并让它显示旅途中的每一点?

完成谷歌地图语法:

$(document).ready(function() {


var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var distancearray=[];
var addresses = [];
addresses.push('Durban, KZN');
addresses.push('izopo, KZN');

warehouse='ladysmith, kwa zulu natal';


function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(-28.5710903, 26.0826083);
  var mapOptions = {
    zoom: 7,
    center: chicago
  };
  map = new google.maps.Map(document.getElementById('route_map_canvas'), mapOptions);
  directionsDisplay.setMap(map);
  calcRoute();
}
var origin = "johannesburg",
  destinations = addresses

service = new google.maps.DistanceMatrixService();

function calcRoute() {
  var waypts = [];
  for (var i = 1; i < destinations.length - 1; i++) {
    waypts.push({
      location: destinations[i],
      stopover: true
    });
  }
  var request = {
    origin: origin,
    destination: destinations[destinations.length - 1],
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var orig = document.getElementById("orig"),
        dest = document.getElementById("dest"),
        dist = document.getElementById("dist");

      orig.value = response.routes[0].legs[0].start_address;
      dest.value = response.routes[0].legs[0].end_address;
      var total_distance = 0.0;
      for (var i = 0; i < response.routes[0].legs.length; i++) {
        total_distance += response.routes[0].legs[i].distance.value;
        distancearray.push([response.routes[0].legs[i].distance.value]);
        //alert(distancearray);
      }
      dist.value = total_distance + " meters";
    }
  });

}
  initialize();

})

一如既往地谢谢,

1 个答案:

答案 0 :(得分:1)

除了destinations变量中只有两个目的地用作开始和结束之外,你已经做了一切正确的事情。 directionsRequest函数中的calcRoute()对象中有零个航点。 这就是你没有得到任何中间航路点而没有标记的原因。

请参阅此updated Fiddle我已将另一个位置推送到addresses变量(第11行)并在地图上正确显示。

您始终可以console.log(request);查看要传递给Google的请求对象。