在Google地图上显示多条路线 [英] Display multiple routes on google map

查看:141
本文介绍了在Google地图上显示多条路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在谷歌地图上显示多条路线,但它只显示一条。你可以请我做错了什么?



< div class =searchmapstyle =float:left; margin-left:1 %id =map>< / div>

  var map = null; 
var markerPoints = [];

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
函数initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById(map),{scrollwheel:false,mapTypeId:google.maps.MapTypeId.ROADMAP,mapTypeControl:false,streetViewControl:false,center:new google。 maps.LatLng(19.0759837,72.87765590000004),zoom:13});


directionsDisplay.setMap(map);



函数calcRoute(flat,flng,tlat,tlng)
{
var start = new google.maps.LatLng(flat,flng );
var end = new google.maps.LatLng(tlat,tlng);

var request = {
origin:start,
destination:end,
travelMode:google.maps.DirectionsTravelMode.DRIVING
};

directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers:false,
suppressInfoWindows:true
});
directionsDisplay.setMap(map);

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

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

calcRoute(19.210430,72.843422,19.109858,72.878433);
calcRoute(19.228977,72.856812,19.117302,72.884041);

您可以让我知道我做错了什么吗?
<在路线图和方向箭头的谷歌地图上显示多个路线
======================================================================================================================================================= ====

点击这里

 ![在图片中你可以看到2条带方向箭头的路线] [ 1] 

< style>
html,body,#map_canvas {margin:0;填充:0;身高:100%}
< / style>


< script type =text / javascriptsrc =http://maps.googleapis.com/maps/api/js?sensor=false>< /脚本>

< script>




var directionsService;
var stepDisplay;

var position;
var marker = [];
var polyline = [];
var poly2 = [];
var poly = null;
var startLocation = [];
var endLocation = [];
var timerHandle = [];




var stops_data = [[{Geometry:{Latitude:23.05242,Longitude:72.53375}},

{Geometry:{Latitude:23.03007,Longitude:72.59664}}

],[{Geometry:{Latitude:23.00959,Longitude:72.56189 }},
{Geometry:{Latitude:23.05754,Longitude:72.55302}}
]];



var a,z,b;

var add;


var speed = 0.000005,wait = 1;
var infowindow = null;


infowindow = new google.maps.InfoWindow();


var myPano;
var panoClient;
var nextPanoId;








var directionsDisplay = [];

directionsDisplay [0] = new window.google.maps.DirectionsRenderer({
suppressMarkers:true

});


directionsDisplay [1] = new window.google.maps.DirectionsRenderer({
suppressMarkers:true

});

var map;
var mapOptions = {center:new google.maps.LatLng(42.5584308,-70.8597732),zoom:3,
mapTypeId:google.maps.MapTypeId.ROADMAP};

函数初始化()
{
map = new google.maps.Map(document.getElementById(map_canvas),mapOptions);


directionsService = new google.maps.DirectionsService();


// Setroute(locations [0],locations [1],directionsDisplay [0]);

// Setroute(locations2 [0],locations2 [1],directionsDisplay [1]);


Tour_startUp(stops_data [0]);

window.tour.loadMap(map,directionsDisplay [0]);
window.tour.fitBounds(stops_data [0],map);



if(stops_data [0] .length> 1)
window.tour.calcRoute(stops_data [0],directionsService,directionsDisplay [0]) ;



Tour_startUp(stops_data [1]);
window.tour.loadMap(map,directionsDisplay [1]);
window.tour.calcRoute(stops_data [1],directionsService,directionsDisplay [1]);
window.tour.fitBounds(stops_data [1],map);





}




函数fx(o)
{
if(o& o.legs)
{
for(l = 0; l {
var leg = o.legs [l];
for(var s = 0; s< leg.steps.length; ++ s)
{
var step = leg.steps [s],
a =(step。 lat.lngs.length)step.lat_lngs [0]:step.start_point,
z =(step.lat_lngs.length)?step.lat_lngs [1]:step.end_point,
dir =((Math。 atan2(z.lng() - a.lng(),z.lat() - a.lat())* 180)/Math.PI)+360,
ico =((dir-(dir% 3))%120);
new google.maps.Marker({
position:a,
icon:new google.maps.MarkerImage('http://maps.google.com/mapfiles/dir_'+ico+ '.png',
新google.maps.Size(24,24),
新google.maps.Point(0,0),
新google.maps.Point(12, 12)
),
map:map,
title:Math.round((dir> 360)?dir-360:dir)+'°'
});






函数Tour_startUp(stops){

// alert('first'+ stops.length); $!
$ b if(!window.tour)window.tour = {
updateStops:function(newStops){
stops = newStops;
},


// map:google map object
// directionsDisplay:google directionsDisplay object(in empty)
loadMap:function(map ,dirdis){
var myOptions = {
zoom:15,
center:new window.google.maps.LatLng(51.507937,-0.076188),//默认伦敦
mapTypeId:window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
dirdis.setMap(map);
},
fitBounds:function(stops_data,map){
var bounds = new window.google.maps.LatLngBounds();

//为每条记录扩展边界
(停止数据中的变量x){
var myLatlng = new window.google.maps.LatLng(stops_data [x] .Geometry。 Latitude,stops_data [x] .Geometry.Longitude);
bounds.extend(myLatlng);
}
map.fitBounds(bounds);
},
calcRoute:function(stops_new,directionsService,dirdis){
var batch = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start,1 stop和8 waypoints
var itemsCounter = 0;
var wayptsExist = stops_new.length> 0;
var time = [];
while(wayptsExist){
var subBatch = [];
var subitemsCounter = 0;

// alert('second'+ stops_new.length);
//alert(stops_new[0].Geometry.Latitude +'====='+ stops_new [0] .Geometry.Longitude);


for(var j = itemsCounter; j subitemsCounter ++;

//alert(stops[j].Geometry.Time);



subBatch.push({
位置:new window.google.maps.LatLng(stops_new [j] .Geometry.Latitude,stops_new [j])。 Geometry.Longitude),
中途停留:true

});

//time.push (stops[j].Geometry.Time);

if(subitemsCounter == itemsPerBatch)
break;
}

itemsCounter + = subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter< stops_new.length;
//如果它再次运行,仍然有点。减去1,然后继续
//在上一段旅程结束时启动
itemsCounter--;
}

//现在我们应该有一个2维数组,其中包含一个路标列表
var combinedResults;
var unsortedResults = [{}]; //保存计数器和结果本身,以便稍后对
var directionsResultsReturned = 0进行排序;




(var k = 0; k var lastIndex =批次[k] .length - 1;
var start =批次[k] [0] .location;
var end =批次[k] [lastIndex] .location;

//修剪数组$ b $中的第一个和最后一个条目var waypts = [];
waypts =批次[k];
waypts.splice(0,1);
waypts.splice(waypts.length - 1,1);

var request =
{
origin:start,
destination:end,
waypoints:waypts,
travelMode:window.google。 maps.TravelMode.WALKING
};

// alert('start'+ start);

// alert('end'+ end);


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



if(status == window.google.maps.DirectionsStatus.OK){


fx(result.routes [0]);

polyline [0 ] = new google.maps.Polyline({
path:[],
strokeColor:'#FFFF00',
strokeWeight:3
});

$ b $ poly2 [0] = new google.maps.Polyline({
path:[],
strokeColor:'#FFFF00',
strokeWeight:3
});


var unsortedResult = {order:kk,result:result};
unsortedResults.push(unsortedResult);

directionsResultsReturned ++;

if(directionsResultsReturned == batches.length)//我们已收到所有结果。放到地图
{
//将返回值排序为正确顺序
unsortedResults.sort(function(a,b){return parseFloat(a.order) - parseFloat(b.order );});
var count = 0; (unsortedResults.hasOwnProperty(key)){
if(count)
for(var key in unsortedResults){
if(unsortedResults [key] .result!= null) == 0)//第一个结果。新建combinedResults对象
combinedResults = unsortedResults [key] .result;
else {
//仅在我的统一对象中构建腿,overview_path和边界。这不是一个完整的
// directionResults对象,但足以在地图上绘制路径,这就是我需要的
combinedResults.routes [0] .legs = combinedResults.routes [0] .legs .concat(unsortedResults [键] .result.routes [0] .legs);
combinedResults.routes [0] .overview_path = combinedResults.routes [0] .overview_path.concat(unsortedResults [key] .result.routes [0] .overview_path);

combinedResults.routes [0] .bounds = combinedResults.routes [0] .bounds.extend(unsortedResults [key] .result.routes [0] .bounds.getNorthEast());
combinedResults.routes [0] .bounds = combinedResults.routes [0] .bounds.extend(unsortedResults [key] .result.routes [0] .bounds.getSouthWest());
}
count ++;
}
}
}
dirdis.setDirections(combinedResults);


var legs = combinedResults.routes [0] .legs;

var path = combinedResults.routes [0] .overview_path;

//alert(path.length);

// alert(legs.length);

//setRoutes(legs[0].start_location,legs[legs.length-1].end_location);



for(var i = 0; i {
var markerletter =A.charCodeAt 0);
markerletter + = i;
markerletter = String.fromCharCode(markerletter);

if(i == 0){

// marker [0] = createMarker2(legs [i] .start_location,start,legs [i] .start_address ,绿色);
}

var steps = legs [i] .steps;

// alert('arrival time:'+ legs [i] .arrival_time.text);

// var duration = steps.duration_in_traffic;

// alert(duration.text);

for(j = 0; j {

var nextSegment = steps [j] .path; (k = 0; k {
polyline [0] .getPath()。push(nextSegment [k]);

;
//bounds.extend(nextSegment[k]);
}
}



// createMarker(directionsDisplay.getMap(),legs [i] .start_location,marker+ i,标记+ i +< br> + legs [i] .start_address,markerletter的一些文本;
}
//标记起点
createMarker(dirdis.getMap(),legs [0] .start_location,marker+0,Start Point< br>+ legs [ 0] .start_address, 'A');


var i = legs.length;
var markerletter =A.charCodeAt(0);
markerletter + = i;
markerletter = String.fromCharCode(markerletter);

//标记为终点
createMarker(dirdis.getMap(),legs [legs.length-1] .end_location,marker+ i,End Point< br> +腿[legs.length-1] .end_address, 'B');

polyline [0] .setMap(map);

// startAnimation(0);
}
}
});
})(k);
}
}
};
}


var icons = new Array();
图标[red] =新增google.maps.MarkerImage(mapIcons / marker_red.png,
//此标记宽20像素,高34像素。 maps.Size(20,34),
//此图片的原点为0,0。
new google.maps.Point(0,0),
//此图片为9,34。
new google.maps.Point(9,34));



函数getMarkerImage(iconStr){

// alert(iconStr); ((typeof(iconStr)==undefined)||(iconStr == null)){
iconStr =red;

if


if(iconStr =='A')
{
//用于开始点


if( !图标[iconStr]){
图标[iconStr] =新增google.maps.MarkerImage(http://www.google.com/mapfiles/dd-start.png,
// This标记宽20像素,高34像素
google.maps.Size(20,34),
//此图片的来源为0,0
new google.maps .Point(0,0),
//此图片的锚点位于6,20。
new google.maps.Point(9,34));


$ b if(iconStr =='B')
{

//为终点
$ b!b
if(!图标[iconStr]){
图标[iconStr] =新增google.maps.MarkerImage(http://www.google.com/mapfiles/dd-end.png ,
//此标记宽20像素,高34像素。
new google.maps.Size(20,34),
//此图像的原点为0,0 。
new google.maps.Point(0,0),
//此图片的锚点位于6,20。
new google.maps.Point(9,34)) ;
}


}
返回图标[iconStr];
}
//标记大小表示为X,Y
的大小,其中图像的原点(0,0)位于
//顶部图像左侧。

//标记的起源,锚点位置和坐标
//沿X方向向右增加,在
//向下Y方向增加。

var iconImage = new google.maps.MarkerImage('mapIcons / marker_red.png',
//此标记宽20像素,高34像素。 maps.Size(20,34),
//此图片的原点为0,0。
new google.maps.Point(0,0),
//此图片为9,34。
new google.maps.Point(9,34));



var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
//阴影图像的水平尺寸较大
//位置和偏移量与主图像相同
new google.maps.Size(37,34),
new google.maps.Point(0,0),
new google.maps.Point(9,34));
//形状定义图标的可点击区域。
//该类型定义了HTML& lt; area& gt;元素'poly',其中
//将多边形描绘为一系列X,Y点。最后的
//坐标通过连接到第一个
//坐标来关闭poly。
var iconShape = {
coord:[9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19 ,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20 ,8,18,4,16,2,15,1,13,0],
类型:'poly'
};


函数createMarker(map,latlng,label,html,color){

// alert(color);
// alert(createMarker(+ latlng +,+ label +,+ html +,+ color +));


var contentString ='< b>'+ label +'< / b>< br>'+ html;


// alert('creatMarker'+ contentString);


var marker = new google.maps.Marker({
position:latlng,
map:map,
shadow:iconShadow,
图标:getMarkerImage(color),
形状:iconShape,
标题:label,
zIndex:Math.round(latlng.lat()* - 100000)<<< 5
});
marker.myname = label;

google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(contentString);
infowindow.open(map,marker);
});


返回标记;
}




google.maps.event.addDomListener(window,'load',initialize);

< / script>

< div id =map_canvas>< / div>


[1]:http://i.stack.imgur.com/yB4Tw.png


I am trying to show multiple routes on google map but It is showing only one. Can you please what I am doing wrong?

<div class="searchmap" style="float:left;margin-left:1%" id="map"></div>

var map          = null;
var markerPoints = [];

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() 
{   
  directionsDisplay = new google.maps.DirectionsRenderer(); 
  map = new google.maps.Map(document.getElementById("map"), {scrollwheel:false, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, center:new google.maps.LatLng(19.0759837, 72.87765590000004), zoom:13});


  directionsDisplay.setMap(map);
}


function calcRoute(flat, flng, tlat, tlng)
{
    var start = new google.maps.LatLng(flat, flng);
    var end   = new google.maps.LatLng(tlat, tlng);     

    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsDisplay = new google.maps.DirectionsRenderer({
        suppressMarkers: false,
        suppressInfoWindows: true
    });
    directionsDisplay.setMap(map);

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

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

calcRoute("19.210430", "72.843422", "19.109858", "72.878433");
calcRoute("19.228977", "72.856812", "19.117302", "72.884041");

Can you please let me know what I am doing wrong?

解决方案

Display multiple routes on google map with waypoints and direction arrow
==============

Click here!

![In image u can see 2 routes with direction arrow][1]

 <style>
    html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
    </style>


     <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

    <script>




      var directionsService;
      var stepDisplay;

      var position;
      var marker = [];
      var polyline = [];
      var poly2 = [];
      var poly = null;
      var startLocation = [];
      var endLocation = [];
      var timerHandle = [];




      var stops_data = [[ {"Geometry":{"Latitude":23.05242,"Longitude":72.53375}},

                          {"Geometry":{"Latitude":23.03007,"Longitude":72.59664}}

                        ] ,[ {"Geometry":{"Latitude":23.00959,"Longitude":72.56189}},
                             {"Geometry":{"Latitude":23.05754,"Longitude":72.55302}}
                           ]];



      var a,z,b;

      var add;


      var speed = 0.000005, wait = 1;
      var infowindow = null;


       infowindow = new google.maps.InfoWindow();


      var myPano;   
      var panoClient;
      var nextPanoId;








          var directionsDisplay = [];

          directionsDisplay[0] = new window.google.maps.DirectionsRenderer({
              suppressMarkers: true

            });


          directionsDisplay[1] = new window.google.maps.DirectionsRenderer({
              suppressMarkers: true

            });

          var map;
          var mapOptions = { center: new google.maps.LatLng(42.5584308, -70.8597732), zoom: 3,
            mapTypeId: google.maps.MapTypeId.ROADMAP };

          function initialize() 
          {
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);


            directionsService = new google.maps.DirectionsService();


         //   Setroute(locations[0],locations[1],directionsDisplay[0]);

           // Setroute(locations2[0],locations2[1],directionsDisplay[1]);


            Tour_startUp(stops_data[0]);

            window.tour.loadMap(map, directionsDisplay[0]);
           window.tour.fitBounds(stops_data[0],map);



            if (stops_data[0].length > 1)
                window.tour.calcRoute(stops_data[0],directionsService, directionsDisplay[0]);



            Tour_startUp(stops_data[1]);
            window.tour.loadMap(map, directionsDisplay[1]);
            window.tour.calcRoute(stops_data[1],directionsService, directionsDisplay[1]);
            window.tour.fitBounds(stops_data[1],map);





          }




    function fx(o)
    {
      if(o && o.legs)
      {
        for(l=0;l<o.legs.length;l++)
        {
          var leg=o.legs[l];
          for(var s=0;s<leg.steps.length;++s)
          {
            var step=leg.steps[s],
                a=(step.lat_lngs.length)?step.lat_lngs[0]:step.start_point,
                z=(step.lat_lngs.length)?step.lat_lngs[1]:step.end_point,
                dir=((Math.atan2(z.lng()-a.lng(),z.lat()-a.lat())*180)/Math.PI)+360,
                ico=((dir-(dir%3))%120);
                new google.maps.Marker({
                  position: a,
                  icon: new google.maps.MarkerImage('http://maps.google.com/mapfiles/dir_'+ico+'.png',
                                              new google.maps.Size(24,24),
                                              new google.maps.Point(0,0),
                                              new google.maps.Point(12,12)
                                             ),
            map: map,
            title: Math.round((dir>360)?dir-360:dir)+'°'
          });

          }
        }
      }
    }


    function Tour_startUp(stops) {

        //  alert('first'+stops.length);     

        if (!window.tour) window.tour = {
            updateStops: function (newStops) {
                stops = newStops;
            },


            // map: google map object
            // directionsDisplay: google directionsDisplay object (comes in empty)
            loadMap: function (map, dirdis) {
                var myOptions = {
                    zoom: 15,
                    center: new window.google.maps.LatLng(51.507937, -0.076188), // default to London
                    mapTypeId: window.google.maps.MapTypeId.ROADMAP
                };
                map.setOptions(myOptions);
                dirdis.setMap(map);
            },
         fitBounds: function (stops_data,map) {
                var bounds = new window.google.maps.LatLngBounds();

                // extend bounds for each record 
                for( var x in stops_data) {
                    var myLatlng = new window.google.maps.LatLng(stops_data[x].Geometry.Latitude, stops_data[x].Geometry.Longitude);
                    bounds.extend(myLatlng);
                }
                map.fitBounds(bounds);
            },
            calcRoute: function (stops_new,directionsService, dirdis) {
                var batches = [];
                var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
                var itemsCounter = 0;
                var wayptsExist = stops_new.length > 0;
                var time= [];
                while (wayptsExist) {
                    var subBatch = [];
                    var subitemsCounter = 0;

                   // alert('second'+stops_new.length);        
            //alert(stops_new[0].Geometry.Latitude +' ===== ' +stops_new[0].Geometry.Longitude);


                    for (var j = itemsCounter; j < stops_new.length; j++) {
                        subitemsCounter++;

                    //alert(stops[j].Geometry.Time);



                        subBatch.push({
                            location: new window.google.maps.LatLng(stops_new[j].Geometry.Latitude, stops_new[j].Geometry.Longitude),
                            stopover: true

                        });

                       //time.push(stops[j].Geometry.Time);

                        if (subitemsCounter == itemsPerBatch)
                            break;
                    }

                    itemsCounter += subitemsCounter;
                    batches.push(subBatch);
                    wayptsExist = itemsCounter < stops_new.length;
                    // If it runs again there are still points. Minus 1 before continuing to
                    // start up with end of previous tour leg
                    itemsCounter--;
                }

                // now we should have a 2 dimensional array with a list of a list of waypoints
                var combinedResults;
                var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
                var directionsResultsReturned = 0;




                for (var k = 0; k < batches.length; k++) {
                    var lastIndex = batches[k].length - 1;
                    var start = batches[k][0].location;
                    var end = batches[k][lastIndex].location;

                    // trim first and last entry from array
                    var waypts = [];
                    waypts = batches[k];
                    waypts.splice(0, 1);
                    waypts.splice(waypts.length - 1, 1);

                    var request = 
                        {
                        origin: start,
                        destination: end,
                        waypoints: waypts,
                        travelMode: window.google.maps.TravelMode.WALKING
                    };

                  //  alert('start'+start);

                 //   alert('end'+end);


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



                            if (status == window.google.maps.DirectionsStatus.OK) {


                                 fx(result.routes[0]);

                                 polyline[0] = new google.maps.Polyline({
                                     path: [],
                                     strokeColor: '#FFFF00',
                                     strokeWeight: 3
                                     });


                                 poly2[0] = new google.maps.Polyline({
                                     path: [],
                                     strokeColor: '#FFFF00',
                                     strokeWeight: 3
                                     });     


                                var unsortedResult = { order: kk, result: result };
                                unsortedResults.push(unsortedResult);

                                directionsResultsReturned++;

                                if (directionsResultsReturned == batches.length) // we've received all the results. put to map
                                {
                                    // sort the returned values into their correct order
                                    unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
                                    var count = 0;
                                    for (var key in unsortedResults) {
                                        if (unsortedResults[key].result != null) {
                                            if (unsortedResults.hasOwnProperty(key)) {
                                                if (count == 0) // first results. new up the combinedResults object
                                                    combinedResults = unsortedResults[key].result;
                                                else {
                                                    // only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
                                                    // directionResults object, but enough to draw a path on the map, which is all I need
                                                    combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
                                                    combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);

                                                    combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
                                                    combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
                                                }
                                                count++;
                                            }
                                        }
                                    }
                                    dirdis.setDirections(combinedResults);


                                    var legs = combinedResults.routes[0].legs;

                                    var path = combinedResults.routes[0].overview_path;

                                    //alert(path.length);

                                 //  alert(legs.length);

                                  //setRoutes(legs[0].start_location,legs[legs.length-1].end_location);



                                    for (var i=0; i < legs.length;i++)
                                        {
                                              var markerletter = "A".charCodeAt(0);
                                              markerletter += i;
                                      markerletter = String.fromCharCode(markerletter);

                                      if (i == 0) { 

                                        //marker[0] = createMarker2(legs[i].start_location,"start",legs[i].start_address,"green");
                                      }

                                      var steps = legs[i].steps;

                                    //  alert('arrival time : '+legs[i].arrival_time.text);

                                //  var duration = steps.duration_in_traffic;

                                  // alert(duration.text);

                                      for (j=0;j<steps.length;j++) 
                                      {

                                          var nextSegment = steps[j].path;

                                          for (k=0;k<nextSegment.length;k++) 
                                              {
                                              polyline[0].getPath().push(nextSegment[k]);
                                              //bounds.extend(nextSegment[k]);
                                                 }
                                      }



                                    //  createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);   
                                    }
                                        // Marker for start point 
                                    createMarker(dirdis.getMap(),legs[0].start_location,"marker"+0,"Start Point<br>"+legs[0].start_address,'A');


                                    var i=legs.length;
                                    var markerletter = "A".charCodeAt(0);
                                      markerletter += i;
                                    markerletter = String.fromCharCode(markerletter);

                                    // marker for End Point 
                                    createMarker(dirdis.getMap(),legs[legs.length-1].end_location,"marker"+i,"End Point <br>"+legs[legs.length-1].end_address,'B');

                                    polyline[0].setMap(map);

                                    //startAnimation(0);  
                                }
                            }
                        });
                    })(k);
                }
            }
        };
    }


    var icons = new Array();
    icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
          // This marker is 20 pixels wide by 34 pixels tall.
          new google.maps.Size(20, 34),
          // The origin for this image is 0,0.
          new google.maps.Point(0,0),
          // The anchor for this image is at 9,34.
          new google.maps.Point(9, 34));



    function getMarkerImage(iconStr) {

    //alert(iconStr);

       if ((typeof(iconStr)=="undefined") || (iconStr==null)) { 
          iconStr = "red"; 
       }

    if(iconStr == 'A')
    {
       // for start point 


       if (!icons[iconStr]) {
          icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/dd-start.png",
          // This marker is 20 pixels wide by 34 pixels tall.
          new google.maps.Size(20, 34),
          // The origin for this image is 0,0.
          new google.maps.Point(0,0),
          // The anchor for this image is at 6,20.
          new google.maps.Point(9, 34));
       } 

    }
    if (iconStr == 'B')
    {

        // for end point


        if (!icons[iconStr]) {
              icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/dd-end.png",
              // This marker is 20 pixels wide by 34 pixels tall.
              new google.maps.Size(20, 34),
              // The origin for this image is 0,0.
              new google.maps.Point(0,0),
              // The anchor for this image is at 6,20.
              new google.maps.Point(9, 34));
           } 


        }
    return icons[iconStr];
    }
      // Marker sizes are expressed as a Size of X,Y
      // where the origin of the image (0,0) is located
      // in the top left of the image.

      // Origins, anchor positions and coordinates of the marker
      // increase in the X direction to the right and in
      // the Y direction down.

      var iconImage = new google.maps.MarkerImage('mapIcons/marker_red.png',
          // This marker is 20 pixels wide by 34 pixels tall.
          new google.maps.Size(20, 34),
          // The origin for this image is 0,0.
          new google.maps.Point(0,0),
          // The anchor for this image is at 9,34.
          new google.maps.Point(9, 34));



      var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
          // The shadow image is larger in the horizontal dimension
          // while the position and offset are the same as for the main image.
          new google.maps.Size(37, 34),
          new google.maps.Point(0,0),
          new google.maps.Point(9, 34));
          // Shapes define the clickable region of the icon.
          // The type defines an HTML &lt;area&gt; element 'poly' which
          // traces out a polygon as a series of X,Y points. The final
          // coordinate closes the poly by connecting to the first
          // coordinate.
      var iconShape = {
          coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
          type: 'poly'
      };


    function createMarker(map, latlng, label, html, color) {

    //alert(color);
    //  alert("createMarker("+latlng+","+label+","+html+","+color+")");


        var contentString = '<b>'+label+'</b><br>'+html;


    //    alert('creatMarker'+contentString);


        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            shadow: iconShadow,
            icon: getMarkerImage(color),
            shape: iconShape,
            title: label,
            zIndex: Math.round(latlng.lat()*-100000)<<5
            });
            marker.myname = label;

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(contentString); 
            infowindow.open(map,marker);
            });


        return marker;
    }




          google.maps.event.addDomListener(window, 'load', initialize);

    </script>

    <div id="map_canvas"></div>


  [1]: http://i.stack.imgur.com/yB4Tw.png

这篇关于在Google地图上显示多条路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆