我想在设置之后更改多边形颜色。但是在用户活动上。
一旦设置了路线颜色,之后它就不会改变,因为在同一个功能中,它会发生变化,但之后,即使变量引用确实存在,也不会改变。
这是小提琴演示:
http://jsfiddle.net/8xq4gd8y/15/
码
setTimeout (function () {
console.log('run');
console.log(directionsRenderer2); // < exist in console log
directionsRenderer2.setOptions({
polylineOptions: {
strokeColor: 'gray'
}
});
}, 90);
答案 0 :(得分:3)
您似乎需要设置DirectionsRenderer的map属性才能让它更改:
setTimeout (function () {
console.log('run');
console.log(directionsRenderer2); // < exist in console log
directionsRenderer2.setOptions({
polylineOptions: {
strokeColor: 'gray'
},
map:map
});
},1000);
代码段
var map;
function renderDirections(result, map) {
var directionsRenderer1 = new google.maps.DirectionsRenderer({
directions: result,
routeIndex: 3,
map: map,
polylineOptions: {
strokeColor: "red"
}
});
console.log("routeindex1 = ", directionsRenderer1.getRouteIndex());
var directionsRenderer2 = new google.maps.DirectionsRenderer({
directions: result,
routeIndex: 1,
map: map,
polylineOptions: {
strokeColor: "blue"
}
});
console.log("routeindex2 = ", directionsRenderer2.getRouteIndex()); //line 17
setTimeout(function() {
console.log('run');
console.log(directionsRenderer2); // < exist in console log
directionsRenderer2.setOptions({
polylineOptions: {
strokeColor: 'gray'
},
map: map
});
}, 1000);
}
function calculateAndDisplayRoute(origin, destination, directionsService, directionsDisplay, map) {
directionsService.route({
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: true
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
renderDirections(response, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function initialize() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(new google.maps.LatLng(51.61793418642200, -0.13678550737318), new google.maps.LatLng(51.15788846699750, -0.16364536053269), directionsService, directionsDisplay, map);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>