我有一张 map ,我想使用 Google Maps Route API 在上面添加计划路线和行驶路线。
我正在做的是获取计划路线的路线并将其添加到 map 中。为此,路线颜色为灰色。然后我添加通常位于计划路线之上的行驶路线。该路线的颜色是蓝色。我将计划路线的不透明度设置为 1,将行驶路线的不透明度设置为 0.75。
有时,当页面加载时,计划的路线位于顶部,有时行驶的路线位于顶部。我猜它是从 Google 获取数据,但由于 Javascript 的性质,它不会按顺序返回。
我正在寻找的是始终在旅行之前完成计划的路线负载。我的计划是监听事件并使用 promise 。
我应该监听哪些事件?
最佳答案
DirectionsRenderer 上唯一可用的事件方向已更改:
Events
directions_changed | Arguments: None
This event is fired when the rendered directions change, either when a new DirectionsResult is set or when the user finishes dragging a change to the directions path.
代码片段:
var map;
var directionsService;
var directionsDisplays = [];
function initMap() {
directionsService = new google.maps.DirectionsService;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {
lat: 41.85,
lng: -87.65
}
});
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplays.push(directionsDisplay);
calculateAndDisplayRoute("New York, NY", "Los Angeles, CA", {
strokeWeight: 8,
strokeOpacity: 1.0,
strokeColor: "white"
}, true);
// directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplays[0], 'directions_changed', function() {
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplays.push(directionsDisplay);
calculateAndDisplayRoute("New York, NY", "Denville,NJ", {
strokeWeight: 4,
strokeOpacity: 0.5,
strokeColor: "blue"
}, false);
});
}
function calculateAndDisplayRoute(start, end, options, preserveViewport) {
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplays[directionsDisplays.length - 1].setOptions({
map: map,
polylineOptions: options,
preserveViewport: preserveViewport
});
directionsDisplays[directionsDisplays.length - 1].setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
关于javascript - 谷歌地图有两条路线重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859759/