Вы можете повторно использовать весь фрагмент кода, если хотите.Предполагая, что весь этот код находится в классе, вы должны определить метод следующим образом:
// TODO: Replace `any` with the correct type for a marker.
setupMarkerClickHandler(marker: any, name: string, address: string, url: string) {
marker.addListener('click', () => {
//create the content
let markerInfoTemplate = `
<span class="title">${name}</span><br>
<span class="address">${address}</span><br>
<button class="text-button">
<a href="${url}">Show route</a>
</button>
`;
this.infowindow.setContent(markerInfoTemplate);
// TODO: Replace `map` with another way of referring to the map (maybe save
// the map in a property of `this`).
this.infowindow.open(map, marker);
//change the markers icons
this.deselectAllMarkers();
marker.setIcon(this.activeIcon);
});
}
Затем вызовите:
this.setupMarkerClickHandler(marker, this.locations[i][0], this.locations[i][3], this.locations[i][4]);
и:
this.setupMarkerClickHandler(currentMarker, place.name, place.adr_address, place.url);
Я заметил, что вы вставляете строки в HTML без экранирования, что может быть проблемой безопасности, если вы не контролируете источник этих строк.Выберите ваше любимое решение, например, здесь , чтобы избежать строк.