通过Google Maps Javascript API,用户可以使用DirectionsService
和DirectionsRenderer
(examples)显示它们之间的标记和方向。
const directionsService = new google.maps.DirectionsService()
const directionsDisplay = new google.maps.DirectionsRenderer()
const mapOptions = {
zoom:7,
center: loc // some coordinates
}
const map = new google.maps.Map(document.getElementById('map'), mapOptions)
directionsDisplay.setMap(map)
const request = {
origin: start, // some coordinates
destination: end, // some coordinates
travelMode: 'DRIVING'
}
directionsService.route(request, function(result, status) {
if (status == 'OK') {
directionsDisplay.setDirections(result)
}
})
上面将在地图上显示两个标记(开始和结束),并在它们之间突出显示路线。我需要的是创建的每个标记的引用(设置自定义标签,注册事件等)。有没有办法在仍然使用directionsDisplay.setDirections(result)
的情况下做到这一点,或者我需要手动创建所有内容?
发布于 2018-06-08 05:33:25
你不能(很容易/安全地)获得对标记的引用。您可以设置DirectionsRenderer
的suppressMarkers
选项,然后根据响应中的数据创建您自己的“自定义”标记。
directionsService.route(request, function(result, status) {
if (status == 'OK') {
directionsDisplay.setDirections(result);
createMarker(result.routes[0].legs[0].start_location, "A", "start marker", map, infowindow);
var lastLeg = result.routes[0].legs.length - 1;
createMarker(result.routes[0].legs[lastLeg].end_location, "B", "end marker", map, infowindow);
}
});
代码片段:
function initialize() {
const directionsService = new google.maps.DirectionsService();
const directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var infowindow = new google.maps.InfoWindow();
const mapOptions = {
zoom: 7,
center: new google.maps.LatLng(37.4419, -122.1419) // some coordinates
}
const map = new google.maps.Map(document.getElementById('map'), mapOptions)
directionsDisplay.setMap(map)
const request = {
origin: {
lat: 37.4418834,
lng: -122.1430195
}, // some coordinates
destination: {
lat: 37.4529598,
lng: -122.1817252
}, // some coordinates
travelMode: 'DRIVING'
}
directionsService.route(request, function(result, status) {
if (status == 'OK') {
directionsDisplay.setDirections(result);
createMarker(result.routes[0].legs[0].start_location, "A", "start marker", map, infowindow);
var lastLeg = result.routes[0].legs.length - 1;
createMarker(result.routes[0].legs[lastLeg].end_location, "B", "end marker", map, infowindow);
}
})
}
google.maps.event.addDomListener(window, "load", initialize);
// Adds a marker to the map.
function createMarker(location, label, content, map, infowindow) {
var marker = new google.maps.Marker({
position: location,
label: label,
title: label,
map: map
});
marker.addListener('click', function(e) {
infowindow.setContent(content);
infowindow.open(map, this);
})
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
https://stackoverflow.com/questions/50750226
复制相似问题