【问题标题】:Google API Multiple Path ColorGoogle API 多路径颜色
【发布时间】:2017-07-09 16:51:33
【问题描述】:

我想将存储在数组中的不同颜色用于在 Google 地图上绘制的不同路径。从我的代码中,我只能为所有路径获得一种颜色。但我希望每条路径都有不同的颜色。Here is the result I am receiving

<body>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=myMap"></script>
<script type="text/javascript">

var myarray=<?php echo json_encode($videosetting); ?>;
document.write("<br>array <br>")
document.write(myarray)
document.write("<br>array[0] <br>")
document.write(myarray[0])

document.write("<br>array[1] <br>")
document.write(myarray[1])

var count= <?php echo $count; ?>;
document.write(count)

var markes=[];

for (var i=0; i<count ;i++) {
    markes[i]= [
        {
            "title": 'Reduit',
            "lat": myarray[i][2],
            "lng": myarray[i][3],
            "description": 'reduit'
        }
    ,
        {
            "title": 'Bagatelle',
            "lat": myarray[i][4],
            "lng": myarray[i][5],
            "description": 'bagatelle'
        }
    ,
            {
            "title": 'Bagatelle',
            "lat": myarray[i][8],
            "lng": myarray[i][9],
            "description": 'bagatelle'
        }
    ,
        {
            "title": 'Reduit',
            "lat": myarray[i][6],
            "lng": myarray[i][7],
            "description": 'reduit'
        }



];
}


window.onload = function () {
    var mapOptions = {
        center: new google.maps.LatLng(markes[0][1].lat, markes[0][1].lng),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
    var infoWindow = new google.maps.InfoWindow();

    var latlngbounds = new google.maps.LatLngBounds();



//Creating Markers


    var data=[];
    var myLatlng=[];
    var marker=[];
    //var lat_lng = new Array();
    var lat_lng = [];
    for (var i=0;i<count; i++) {
           for (j = 0; j < markes[i].length; j++) {
        data[j] = markes[i][j];
        myLatlng[j] = new google.maps.LatLng(data[j].lat, data[j].lng);
        lat_lng.push(myLatlng[j]);
        //lat_lng[j]=myLatlng[j];
        marker[j] = new google.maps.Marker
            (
                {
                 position: myLatlng[j],
                    map: map,
                title: data[j].title

                }
            );


        latlngbounds.extend(marker[j].position);

        (
            function (marker, data) 
            {
              google.maps.event.addListener
              ( marker, "click", function (e) 
                        {
                                infoWindow.setContent(data.description);
                                infoWindow.open(map, marker);
                        }
                    );
            }
            )(marker[j], data[j]);
    }
    map.setCenter(latlngbounds.getCenter());
    map.fitBounds(latlngbounds);
    }



    //Initialize the Path Array


    //Initialize the Direction Service


    //Set the Path Stroke Color

   var color=['#0EF022','#FF0000','#FFFF00','#00FF00','#00FFFF','#0000FF','#000000','FFFFFF'];
   var src_des=[];
   var j=0;
   for (i=0;i<lat_lng.length;i++) {
    src_des[j]=[lat_lng[i],lat_lng[i+1]];

    j+=1;
    i+=1;
   }





 for (var t = 0;t < src_des.length; t++) 
 {
 //Intialize the Direction Service
 var service = new google.maps.DirectionsService();
 var directionsDisplay = new google.maps.DirectionsRenderer();

 var bounds = new google.maps.LatLngBounds();
 if ((t + 1) < lat_lng.length) 
 {
  var src = src_des[t][0];
  var des = src_des[t][1];
  service.route(
  {
    origin: src,
    destination: des,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  }, 
  function(result, status) 
  {
    if (status == google.maps.DirectionsStatus.OK) 
    {
      // new path for the next result
      var path = new google.maps.MVCArray();
      //Set the Path Stroke Color
      // new polyline for the next result
      var poly = new google.maps.Polyline(
      {
        map: map,
        strokeColor: color[t]
      });
      poly.setPath(path);
      for (var k = 0, len = result.routes[0].overview_path.length; k < len; k++) 
      {
        path.push(result.routes[0].overview_path[k]);
        bounds.extend(result.routes[0].overview_path[k]);
        map.fitBounds(bounds);
      }
    } else alert("Directions Service failed:" + status);
  });
  }
 }






 }// window.onload = function () 
 </script>
<div id="dvMap" style="width: 100%; height: 800px">
</div>

【问题讨论】:

    标签: javascript php html google-maps google-maps-api-3


    【解决方案1】:

    另外,如果我喜欢 geocodezip 中的代码和解释,这里有一个替代方案,它为您提供了始终更改颜色的高度灵活性,尤其是在您不知道最终编写了多少条路径的情况下。用以下代码替换您的颜色数组:

    var colorIndex_ = 0;
    var COLORS = [["red", "#ff0000"], ["green","#008000"], ["blue", "#000080"], ["purple", "#800080"],
            ["light-purple", "#FF00FF"], ["brown", "#0xB70000"], ["light-green", "#00F000"], ["cyan", "#00FFFF"]];
    
    function getColor(named) {
        return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
    } 
    

    在您的折线定义中 replace: strokeColor: color[t] with: strokeColor: getColor(false)

    就是这样。我已经根据 geocodezip 中的示例测试了代码 - 工作正常。因此,如果您需要一个工作示例,请告诉我。兄弟,莱因哈德

    【讨论】:

      【解决方案2】:

      这是遍历调用异步服务的循环的常见问题。一种解决方案(如Google Maps JS API v3 - Simple Multiple Marker Example的答案所示)是使用函数闭包将循环变量与回调函数实例关联起来:

      for (var t = 0; t < src_des.length; t++) {
        //Intialize the Direction Service
        var service = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();
      
        var bounds = new google.maps.LatLngBounds();
        if ((t + 1) < lat_lng.length) {
          var src = src_des[t][0];
          var des = src_des[t][1];
          service.route({
              origin: src,
              destination: des,
              travelMode: google.maps.DirectionsTravelMode.DRIVING
            },
            // function closure on "color"
            (function(color) {
              return function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                  // new path for the next result
                  var path = new google.maps.MVCArray();
                  //Set the Path Stroke Color
                  // new polyline for the next result
                  var poly = new google.maps.Polyline({
                    map: map,
                    strokeColor: color
                  });
                  poly.setPath(path);
                  for (var k = 0, len = result.routes[0].overview_path.length; k < len; k++) {
                    path.push(result.routes[0].overview_path[k]);
                    bounds.extend(result.routes[0].overview_path[k]);
                    map.fitBounds(bounds);
                  }
                } else alert("Directions Service failed:" + status);
              }
            // the value for this callback function
            }(color[t])))
        };  
      }
      

      proof of concept fiddle

      【讨论】:

      • 非常感谢 geocodezip 和 Reinhard。现在工作正常。问候
      • accept the answer 对解决您的问题最有用。
      猜你喜欢
      • 1970-01-01
      • 2016-11-30
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      相关资源
      最近更新 更多