在谷歌地图v3上更改多重折线笔触颜色

时间:2012-01-24 10:20:40

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

我需要创建多条折线,每条折线都有自己的颜色,并且它们的标记相互连接,我正在使用谷歌地图v3。

例如,我有五个标记,它们都通过红色折线相互连接。现在我想在多种配色方案中显示这种红色折线,第一个折线为绿色,第二个为蓝色,第三个为黑色,依此类推。

这是我的代码

<script type='text/javascript'>
var poly;
var map;
var path;
var i = parseInt(0, 10);
var marker;          

function initialize() {
  var chicago = new google.maps.LatLng(41.879535, -87.624333);
  var myOptions = {
    zoom: 7,
    center: chicago,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
  var polyOptions = {
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3
  }
  poly = new google.maps.Polyline(polyOptions);
  poly.setMap(map);
  // Add a listener for the click event
  google.maps.event.addListener(map, 'click', addLatLng);
}

/**
* Handles click events on a map, and adds a new point to the Polyline.
* @param {MouseEvent} mouseEvent
*/
function addLatLng(event) {
  i++;
  //var path = poly.getPath();
  path = poly.getPath();
  var polyOptions2 = {
    strokeColor: '#FFFFFF',
    strokeOpacity: 1.0,
    strokeWeight: 3
  }
  if (i == 2) {
    poly.setOptions(polyOptions2);

  }
  else {
    polyOptions2.strokeColor = "#FF0000";
    poly.setOptions(polyOptions2);
  }
  path.push(event.latLng);
  // Add a new marker at the new plotted point on the polyline.
  marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),
    map: map
  });
}
</script>

2 个答案:

答案 0 :(得分:2)

将折线的标记选项和颜色加载到json数组中,然后循环创建标记和折线。

希望这能让你前进。

答案 1 :(得分:1)

将代码的这部分设置为for循环,如

       var colorVariable = ["red","green","blue","yellow","black"];

        for(var a =0;a<=5;a++){
              var polyOptions = {
                strokeColor: colorVariable[a],
                strokeOpacity: 1.0,
                strokeWeight: 2
              }
              poly = new google.maps.Polyline(polyOptions);
              poly.setMap(map);
        }

它会正常工作