Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Si vous avez une mise en page qui doit changer lorsque la vue détaillée sur ce lieu est affichée, utilisez les écouteurs d'événements placedetailsviewshowstart et placedetailsviewhidestart. Dans l'exemple ci-dessous, trois quartiers sont indiqués par des repères personnalisés. Lorsque l'utilisateur clique sur l'un de ces repères, une InfoWindow s'ouvre et décrit le quartier. Si un utilisateur clique sur un POI lorsqu'une InfoWindow est ouverte, l'InfoWindow se ferme lorsque la vue détaillée sur ce POI s'affiche, puis s'ouvre à nouveau lorsque l'utilisateur ferme la vue.
Afficher le code source
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>
Gérer une InfoWindow avec des événements de vue détaillée sur le lieu
Lorsque la vue détaillée sur le lieu s'ouvre et que vous appelez InfoWindow.close(), l'InfoWindow ouverte est supprimée du DOM. Pour créer l'effet de "réouverture" de l'InfoWindow, vous devez stocker les propriétés de l'InfoWindow dans une variable en dehors du DOM afin de pouvoir recréer l'InfoWindow lorsque vous voulez l'afficher à nouveau. Le meilleur moment pour enregistrer les informations dans une variable de stockage est celui de la création de l'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,
};
}
Plus tard, lorsque la vue détaillée sur le lieu sera fermée, vous pourrez appeler la même fonction de création de l'InfoWindow pour recréer la dernière InfoWindow ouverte.
Étant donné que l'utilisateur peut choisir parmi plusieurs repères de quartier sur cette carte, nous utilisons ces lignes dans l'écouteur de clics du repère pour définir le dernier quartier ayant enregistré un clic comme point de départ de directionsOptions. Cela démontre que directionsOptions peut être mis à jour même après l'initialisation de localContextMapView.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.