如何更改返回的Google地图方向上的虚线颜色

时间:2013-09-21 23:12:25

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

使用Google路线服务我在两个地点之间获得公交结果,并在地图上显示结果。我想改变两个位置之间的线条颜色。我正在使用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);
    }
  });
}

1 个答案:

答案 0 :(得分:2)

虽然它没有被G记录,但google.maps.DirectionsRenderer确实通过其属性b.polylines公开其折线,这是一个google.maps.Polyline实例数组。因此,如果我们搜索它们,我们发现只有虚线的那些具有'icons'属性,我们可以通过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);

我应该注意,上面应该在设置directionsDisplay的指示后完成。

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