3

使用谷歌路线服务,我得到两个地点之间的交通结果,并在地图上显示结果。我想更改两个位置之间的线条颜色的颜色。我正在使用 google.maps.Polyline 更改主线颜色,但是有些部分的线是虚线的(以显示您必须步行的位置),但这并没有更改为与主线相同的颜色。我该怎么做才能改变虚线的颜色?

/* change line color */
var polylineOptionsActual = new google.maps.Polyline({
  strokeColor: '#9f98ff',
  strokeWeight: 5
});

function initialize() {
  /* create map */
  var mapOptions = {
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  /* directions */
  var rendererOptions = { 
    map: map, 
    suppressMarkers: true,
    polylineOptions: polylineOptionsActual
  } 
  directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
  directionsDisplay.setPanel(document.getElementById('directions-results'));
}

function getDirections() {
  /* directions request */
  var request = {
    origin: document.getElementById('from-input').value,
    destination: document.getElementById('to-input').value,
    travelMode: google.maps.TravelMode.TRANSIT
  };

  /* display directions */
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}
4

1 回答 1

2

尽管 G 没有记录它,但 google.maps.DirectionsRenderer 确实通过其属性 b.polylines 公开其折线,该属性是 google.maps.Polyline 实例的数组。因此,如果我们搜索它们,我们会发现只有虚线的那些具有“图标”属性,我们可以通过 google.maps.Polyline.setOptions() 对其进行更改 在代码的全局范围内包含以下内容:

//iconSequence must be a single instance of google.maps.IconSequence object
google.maps.DirectionsRenderer.prototype.setDottedPolylineOptions = function (iconSequence) {
     //need a reference to the current 'this' object
    var obj = this;
     //in case this DirectionsRenderer's directions were just set an instant ago,
     //need a slight delay before we may access the b.polylines property of this object
    window.setTimeout(function () {
        var i,
            lines = obj.b.polylines,
            len = lines.length;
        for (i = 0; i < len; i++) {
            if (lines[i].icons) {
                lines[i].setOptions(
                    {
                        icons: [iconSequence]
                    }
                );
            }
        }
    },1);
};

然后你可以在你的代码中做:

var iconSequence = {
    icon: {
        fillColor: 'red', //or hexadecimal color such as: '#FF0000'
        fillOpacity: 0.8,
        scale: 3,
        strokeColor: 'blue',
        strokeWeight: 1,
        strokeOpacity: 0.8,
        path: google.maps.SymbolPath.CIRCLE
    },
    repeat: '10px'
};
directionsDisplay.setDottedPolylineOptions(iconSequence);

我应该注意,上述操作应在设置方向显示的方向之后完成。

这是一个小提琴:http: //jsfiddle.net/Wx9XV/

于 2013-09-22T10:52:28.957 回答