/
index.js
99 lines (89 loc) · 2.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
// [START maps_boundaries_click_event]
let map;
let featureLayer;
let infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 39.23, lng: -105.73 },
zoom: 8,
// In the cloud console, configure this Map ID with a style that enables the
// "Administrative Area Level 2" Data Driven Styling type.
mapId: "a3efe1c035bad51b", // <YOUR_MAP_ID_HERE>,
});
//[START maps_boundaries_click_event_add_layer]
// Add the feature layer.
//@ts-ignore
featureLayer = map.getFeatureLayer("ADMINISTRATIVE_AREA_LEVEL_2");
// Add the event listener for the feature layer.
featureLayer.addListener("click", handlePlaceClick);
//[END maps_boundaries_click_event_add_layer]
infoWindow = new google.maps.InfoWindow({});
// Apply style on load, to enable clicking.
applyStyleToSelected();
}
// [START maps_boundaries_click_event_handler]
// Handle the click event.
async function handlePlaceClick(event) {
let feature = event.features[0];
if (!feature.placeId) return;
// Apply the style to the feature layer.
applyStyleToSelected(feature.placeId);
// Add the info window.
const place = await feature.fetchPlace();
let content =
'<span style="font-size:small">Display name: ' +
place.displayName +
"<br/> Place ID: " +
feature.placeId +
"<br/> Feature type: " +
feature.featureType +
"</span>";
updateInfoWindow(content, event.latLng);
}
// [END maps_boundaries_click_event_handler]
// [START maps_boundaries_click_event_style]
// Stroke and fill with minimum opacity value.
//@ts-ignore
const styleDefault = {
strokeColor: "#810FCB",
strokeOpacity: 1.0,
strokeWeight: 2.0,
fillColor: "white",
fillOpacity: 0.1, // Polygons must be visible to receive click events.
};
// Style for the clicked Administrative Area Level 2 polygon.
//@ts-ignore
const styleClicked = {
...styleDefault,
fillColor: "#810FCB",
fillOpacity: 0.5,
};
// [END maps_boundaries_click_event_style]
// Apply styles to the map.
function applyStyleToSelected(placeid) {
// Apply styles to the feature layer.
featureLayer.style = (options) => {
// Style fill and stroke for a polygon.
if (placeid && options.feature.placeId == placeid) {
return styleClicked;
}
// Style only the stroke for the entire feature type.
return styleDefault;
};
}
// Helper function to create an info window.
function updateInfoWindow(content, center) {
infoWindow.setContent(content);
infoWindow.setPosition(center);
infoWindow.open({
map,
shouldFocus: false,
});
}
window.initMap = initMap;
// [END maps_boundaries_click_event]