Если макет должен меняться при отображении сведений о месте, используйте прослушиватели событий placedetailsviewshowstart и placedetailsviewhidestart. В примере ниже есть три района, обозначенных специальными маркерами. Когда пользователь нажимает на один из этих маркеров, появляется InfoWindow с описанием района. Если пользователь нажимает на объект инфраструктуры, когда отображается окно InfoWindow, оно закроется при появлении представления со сведениями о месте и откроется снова, когда пользователь закроет представление.
Посмотреть исходный код
TypeScript
let map: google.maps.Map;
let infoWindow;
let infoStorage;
const districts = {
a: {
label: "1",
location: {
lat: -1.283975,
lng: 36.818797,
},
name: "Central",
description:
"The Central Business District is a hub of economic activity during the day and a destination for great food at night.",
},
b: {
label: "2",
location: {
lat: -1.270955,
lng: 36.810857,
},
name: "Westlands",
description:
"With many high-end restaurants and a vibrant nightlife, Westlands attracts young professionals and their families. ",
},
c: {
label: "3",
location: {
lat: -1.311868,
lng: 36.838624,
},
name: "South",
description:
"Known for high-rise apartment buildings, South B and South C are in high demand.",
},
};
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: [
{ type: "restaurant" },
{ type: "tourist_attraction" },
],
maxPlaceCount: 12,
});
map = localContextMapView.map!;
map.setOptions({
center: districts["a"].location,
zoom: 13,
});
// Add 3 custom markers that open InfoWindows on click
for (const key in districts) {
const district = districts[key];
const marker = new google.maps.Marker({
label: district.label,
position: district.location,
map: map,
zIndex: 30,
});
marker.addListener("click", () => {
// Close any open details or existing InfoWindows
localContextMapView.hidePlaceDetailsView();
if (infoWindow) {
infoWindow.close();
}
// Create and open a new InfoWindow
createInfoWindow(district, marker);
// Define origin as the selected marker position
localContextMapView.directionsOptions = {
origin: district.location,
};
});
}
// Set the LocalContextMapView event handlers.
localContextMapView.addListener("placedetailsviewshowstart", () => {
if (infoWindow) {
infoWindow.close();
}
});
localContextMapView.addListener("placedetailsviewhidestart", () => {
if (infoStorage) {
createInfoWindow(infoStorage.district, infoStorage.marker);
}
});
}
// Creates an infoWindow and also stores information associated with the
// InfoWindow so the InfoWindow can be restored after it has been closed
// by non-user-initiated events.
function createInfoWindow(district, marker) {
// Build the content of the InfoWindow
const contentDiv = document.createElement("div");
const nameDiv = document.createElement("div");
const descriptionDiv = document.createTextNode(district.description);
contentDiv.classList.add("infowindow-content");
nameDiv.classList.add("title");
nameDiv.textContent = district.name;
descriptionDiv.textContent = district.description;
contentDiv.appendChild(nameDiv);
contentDiv.appendChild(descriptionDiv);
// Create and open a new InfoWindow
infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(contentDiv);
infoWindow.open(map, marker);
// Store key properties of the InfoWindow for future restoration
infoStorage = {
district: district,
marker: marker,
};
// Clear content storage if infoWindow is closed by the user
infoWindow.addListener("closeclick", () => {
if (infoStorage) {
infoStorage = null;
}
});
}
declare global {
interface Window {
initMap: () => void;
}
}
window.initMap = initMap;
let map;
let infoWindow;
let infoStorage;
const districts = {
a: {
label: "1",
location: {
lat: -1.283975,
lng: 36.818797,
},
name: "Central",
description:
"The Central Business District is a hub of economic activity during the day and a destination for great food at night.",
},
b: {
label: "2",
location: {
lat: -1.270955,
lng: 36.810857,
},
name: "Westlands",
description:
"With many high-end restaurants and a vibrant nightlife, Westlands attracts young professionals and their families. ",
},
c: {
label: "3",
location: {
lat: -1.311868,
lng: 36.838624,
},
name: "South",
description:
"Known for high-rise apartment buildings, South B and South C are in high demand.",
},
};
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: [
{ type: "restaurant" },
{ type: "tourist_attraction" },
],
maxPlaceCount: 12,
});
map = localContextMapView.map;
map.setOptions({
center: districts["a"].location,
zoom: 13,
});
// Add 3 custom markers that open InfoWindows on click
for (const key in districts) {
const district = districts[key];
const marker = new google.maps.Marker({
label: district.label,
position: district.location,
map: map,
zIndex: 30,
});
marker.addListener("click", () => {
// Close any open details or existing InfoWindows
localContextMapView.hidePlaceDetailsView();
if (infoWindow) {
infoWindow.close();
}
// Create and open a new InfoWindow
createInfoWindow(district, marker);
// Define origin as the selected marker position
localContextMapView.directionsOptions = {
origin: district.location,
};
});
}
// Set the LocalContextMapView event handlers.
localContextMapView.addListener("placedetailsviewshowstart", () => {
if (infoWindow) {
infoWindow.close();
}
});
localContextMapView.addListener("placedetailsviewhidestart", () => {
if (infoStorage) {
createInfoWindow(infoStorage.district, infoStorage.marker);
}
});
}
// Creates an infoWindow and also stores information associated with the
// InfoWindow so the InfoWindow can be restored after it has been closed
// by non-user-initiated events.
function createInfoWindow(district, marker) {
// Build the content of the InfoWindow
const contentDiv = document.createElement("div");
const nameDiv = document.createElement("div");
const descriptionDiv = document.createTextNode(district.description);
contentDiv.classList.add("infowindow-content");
nameDiv.classList.add("title");
nameDiv.textContent = district.name;
descriptionDiv.textContent = district.description;
contentDiv.appendChild(nameDiv);
contentDiv.appendChild(descriptionDiv);
// Create and open a new InfoWindow
infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(contentDiv);
infoWindow.open(map, marker);
// Store key properties of the InfoWindow for future restoration
infoStorage = {
district: district,
marker: marker,
};
// Clear content storage if infoWindow is closed by the user
infoWindow.addListener("closeclick", () => {
if (infoStorage) {
infoStorage = null;
}
});
}
window.initMap = initMap;
/*
* Always set the map height explicitly to define the size of the div element
* that contains the map.
*/
#map {
height: 100%;
}
/*
* Optional: Makes the sample page fill the window.
*/
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.infowindow-content {
width: 300px;
}
.title {
font-size: x-large;
font-weight: bold;
}
<html>
<head>
<title>Local Context Events</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="map"></div>
<!--
The `defer` attribute causes the callback to execute after the full HTML
document has been parsed. For non-blocking uses, avoiding race conditions,
and consistent behavior across browsers, consider loading using Promises.
See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
for more information.
-->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=localContext&v=beta"
defer
></script>
</body>
</html>
Управление InfoWindow с событиями просмотра сведений о месте
Когда открывается представление со сведениями о месте и вы вызываете InfoWindow.close(), открытое окно InfoWindow удаляется из DOM. Чтобы создать эффект повторного открытия окна InfoWindow, свойства InfoWindow нужно сохранить в переменной за пределами DOM. Это позволит воссоздать состояние InfoWindow, когда вы захотите снова его показать. Лучше всего сохранить информацию в переменную для хранения при создании InfoWindow.
let infoStorage;
function createInfoWindow(district, marker) {
// Build the content of the InfoWindow
let contentDiv = document.createElement('div');
...
// Create and open a new InfoWindow
infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(contentDiv);
infoWindow.open(map, marker);
// Store key properties of the InfoWindow for future restoration
infoStorage = {
'district': district,
'marker': marker,
};
}
Позже, когда представление со сведениями о месте будет закрыто, вы сможете вызвать ту же функцию создания InfoWindow, чтобы воссоздать последнее окно InfoWindow, которое было открыто.
Поскольку на этой карте несколько маркеров районов, из которых пользователь может выбрать нужный, исходную точку для directionsOptions можно обновить в зависимости от последнего выбранного района с помощью приведенных ниже строк кода в прослушивателе кликов для маркера. В этом коде показано, как можно обновить directionsOptions даже после инициализации localContextMapView.