GoogleMaps - сделать так, чтобы infoWindows появлялись (angularjs)
Мне было интересно, если вы могли бы помочь мне. Через угловой JS v1 у меня есть карта, встроенная в мою веб-страницу, которая:
- Позволяет пользователю ввести источник и пункт назначения.
- Наносит маркеры и отображает маршрут от пункта отправления до пункта назначения.
- Отображает рестораны (в виде маркеров) для путевых точек в месте отправления, назначения, а также в средней путевой точке. (Таким образом, 3 балла, я не должен чрезмерно использовать запросы / ограничения Google API.
Проблема: Когда я нажимаю на свои маркеры, мое информационное окно не появляется. Похоже, что по умолчанию они появляются для пунктов отправления и назначения, но я не могу понять, как заставить их отображаться во всех ресторанах, которые отображаются в виде маркеров. (Использовал PlaceSearch для этого).
Я много гуглил, но поскольку я новичок в JS/Angular, я не могу найти лучший подход.
Мой код директивы ниже, с некоторым кодом infoWindow, но, как вы можете видеть, я в тупике. Не уверен, что мне нужен обработчик кликов?
googleMap.$inject = [];
function googleMap() {
return {
restrict: 'E',
template: '<div class="google-map"></div>',
replace: true,
scope: {
center: '=',
zoom: '=',
origin: '=',
destination: '=',
travelMode: '='
},
link($scope, $element) {
const map = new google.maps.Map($element[0], {
zoom: $scope.zoom,
center: $scope.center
});
const directionsService = new google.maps.DirectionsService();
const directionsDisplay = new google.maps.DirectionsRenderer();
const placesService = new google.maps.places.PlacesService(map);
// const infoWindows = [];
// const infowindow = new google.maps.InfoWindow();
// let marker = new google.maps.Marker;
directionsDisplay.setMap(map);
$scope.$watch('center', () => map.setCenter($scope.center), true);
$scope.$watchGroup(['origin', 'destination', 'travelMode'],
displayRoute);
// DISPLAY ROUTE
function displayRoute() {
if(!$scope.origin || !$scope.destination || !$scope.travelMode)
return false;
directionsService.route({
origin: $scope.origin,
destination: $scope.destination,
travelMode: $scope.travelMode
}, (response) => {
directionsDisplay.setDirections(response);
// beginning of this form
// response.routes[0].legs[0].steps.map(step => {
const steps = response.routes[0].legs[0].steps
const lookup = [steps[0], steps[Math.round(steps.length / 2)],
steps[steps.length - 1]]
lookup.map(step => {
placesService.nearbySearch({
location: step.start_point,
radius: 50,
type: ['restaurant'],
openNow: true
}, (results) => {
results.map(place => {
console.log(place.name);
return new google.maps.Marker({
map: map,
position: place.geometry.location,
// label: '⭐️',
title: place.name
}); //google maps marker
});
results.map(place => {
console.log(place.vicinity);
const contentString = place.name;
return new google.maps.InfoWindow({
title: place.name,
content: contentString
}); //google maps marker
// infoWindows.push(infowindow);
});
});
}); //end of this function
}); //end return directionsdisplay
} //display route ends
} //link scope ends
};
}
export default googleMap;
Спасибо!
1 ответ
Один из способов сделать это - создать информационное окно и маркер, а затем привязать событие щелчка, чтобы открыть / закрыть информационное окно.
var marker = new google.maps.Marker({
position: latlng,
map: mapObject,
title: "MARKER"
});
var infoWindow = new google.maps.InfoWindow({
content: "<h1>Hello World</h1>"
});
google.maps.event.addListener(marker, "click", function () {
infoWindow.open(mapObject, marker);
});
РЕДАКТИРОВАТЬ - В вашем случае вы строите массив / список маркеров, и каждый маркер имеет свое собственное информационное окно - так что вы можете изменить код Plotting of Markers (результаты) на что-то вроде этого:
Примечание: компилятор не используется, может содержать синтаксические ошибки
// keep reference of plotted markers, so we can clear them if required
var markers = [];
for (var i = 0; i < results.length; i++) {
var place = results[i];
// create marker
var marker = new google.maps.Marker({
map: mapObject,
position: place.geometry.location,
title: place.name
});
// create info window
var infoWindow = new google.maps.InfoWindow({
content: ''
});
//adding an extra property to marker, (infoWindow - so we can get it inside click event of marker
marker.infoWindow = infoWindow;
// click event handler
google.maps.event.addListener(marker, "click", function() {
// this == marker
var map = this.infoWindow.getMap();
if (map !== null && typeof map !== "undefined")
this.infoWindow.close();
else {
// open info window at marker position
this.infoWindow.open(mapObject, this);
}
});
markers.push(marker);
}