在google-map中绘制多行

时间:2013-10-07 12:55:58

标签: javascript google-maps polyline

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

任何人都可以告诉我一些解决方案吗

SEE - 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);}
}

1 个答案:

答案 0 :(得分:0)

有些问题与此问题无关:

  1. 您在每次迭代时创建一个新的Map实例
  2. 您没有设置渲染器的地图属性
  3. 您已将routeIndex设置为1,但只获得1条路线(索引为0)
  4. 与问题有关的问题:尝试很好,但实施并非如此 您必须为每个请求创建一个新的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/