0

我已经在谷歌地图中绘制了一条折线,但是当试图在单个地图中绘制两条线时它失败了......它在谷歌地图上没有显示任何内容

谁能告诉我一些解决方案

见-http: //jsfiddle.net/wLeBh/12/

我的 javascript 如下所示

function initMap()
{
    alert("entered!!!");
var routes = [{origin:'p t usha road, kozhikode', 
               destination:'cooperative hospital, eranjipalam, kozhikode'
              }, 
              {origin:'IIM, Kozhikode',
               destination:'VELLIMADUKUNNU, KOZHIKODE'
              }
             ];    
   try{          
    var rendererOptions = {
    preserveViewport: true,         
    suppressMarkers:true,
    routeIndex:1
    };  

     var directionsService = new google.maps.DirectionsService();
     var directionsDisplay = new google.maps.DirectionsRenderer();

//routes.each(function(route){


for (var i = 0, l = routes.length; i < l; i++) {
        var obj = routes[i];
alert(obj.origin);
    var request = {
        origin: obj.origin,
        destination: obj.destination,
        travelMode: google.maps.TravelMode.DRIVING
    };


 map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0,0),
zoom: 10,
maxZoom:16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions:
{
   style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
 }
 });


    var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    directionsDisplay.setMap(map);

    directionsService.route(request, function(result, status) {
    console.log(result);

        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
        }
    });


}

}catch(e){alert(e);}
}
4

1 回答 1

0

有一些与问题无关的问题:

  1. 您在每次迭代时创建一个新的 Map-instance
  2. 你没有设置渲染器的地图属性
  3. 您已将 routeIndex 设置为 1,但您仅获得 1 条路线(索引为 0)

与问题相关的问题:尝试是好的,但实施不是。
您必须为每个请求创建一个新的 DirectionsRenderer 实例(您已经完成了),但是这个实例在函数范围内是可见的,因此该变量将在每次迭代时被覆盖,并且当响应到达时每个响应都将使用相同的DirectionsRenderer-instance(可能只渲染一条路线)。

使用匿名函数创建 DirectionsRenderer 实例和请求:

$.each(routes,
function(i,obj){//<--anonymous function

var request = {
        origin: obj.origin,
        destination: obj.destination,
        travelMode: google.maps.TravelMode.DRIVING
      }, 
    //directionsDisplay is only visible in the scope of this anonymous function    
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);


    directionsService.route(request, function(result, status) {

      if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(result);
      }
    });  

});});

小提琴:http: //jsfiddle.net/doktormolle/wLeBh/14/

于 2013-10-07T15:26:10.720 回答