Вы не можете (легко / безопасно) получить ссылки на маркеры.Вы можете установить suppressMarkers
параметр DirectionsRenderer
, а затем создать свои собственные "пользовательские" маркеры из данных в ответе.
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"></script>
<div id="map"></div>