路线建成后如何在谷歌地图api中更改路线的颜色 [英] how to change color of route in google map api after route is build
问题描述
您会发现许多已经存在的答案,显示了如何在其上构建具有不同颜色的路线 如何更改谷歌地图 v3 中路线的颜色
You will find many already answers showing how to build route with different colors on it how to change the color of route in google maps v3
我想知道如何在已经构建和渲染后更改颜色.
I want to know how I can change the color once its already builded and rendered.
我在地图上显示了许多不同的路线,但我想显示红色或更深的颜色,如果此方向点处于活动状态并将其他路线颜色更改为灰色,直到其中一个处于活动状态.
I have many different routes showing on the map, but I want to show red color or darker color, if this direction point is active and change other route colors to gray, until one of them are active.
代码:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: "red"
}
});
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: {lat: 41.850033, lng: -87.6500523}
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
演示如何不使用两条路线:http://jsfiddle.net/8xq4gd8y/15/
demo to show how its not working with two routes: http://jsfiddle.net/8xq4gd8y/15/
推荐答案
directionsRenderer
类有一个 setOptions
方法.请参阅文档.
The directionsRenderer
class has a setOptions
method. See the documentation.
directionsDisplay.setOptions({
polylineOptions: {
strokeColor: 'red'
}
});
要使其正常工作,您需要将其从地图中移除并重新添加以查看颜色变化.
For this to work, you need to remove it from the map and add it back to see the color change.
例如在事件侦听器中,您可以:
For example in an event listener, you would do:
google.maps.event.addListener(map, 'click', function() {
directionsDisplay.setMap(null);
directionsDisplay.setOptions({
polylineOptions: {
strokeColor: 'blue'
}
});
directionsDisplay.setMap(map);
});
这篇关于路线建成后如何在谷歌地图api中更改路线的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!