Skip to content

Commit 81e59f0

Browse files
authored
feat: Migrates the boundaries-click sample. (#879)
* feat: Migrates the boundaries-click sample. * Update Google Maps API key in index.html
1 parent 15361f8 commit 81e59f0

File tree

6 files changed

+271
-0
lines changed

6 files changed

+271
-0
lines changed

samples/boundaries-click/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Google Maps JavaScript Sample
2+
3+
This sample is generated from @googlemaps/js-samples located at
4+
https://github.com/googlemaps-samples/js-api-samples.
5+
6+
## Setup
7+
8+
### Before starting run:
9+
10+
`npm i`
11+
12+
### Run an example on a local web server
13+
14+
`cd samples/boundaries-click`
15+
`npm start`
16+
17+
### Build an individual example
18+
19+
`cd samples/boundaries-click`
20+
`npm run build`
21+
22+
From 'samples':
23+
24+
`npm run build --workspace=boundaries-click/`
25+
26+
### Build all of the examples.
27+
28+
From 'samples':
29+
30+
`npm run build-all`
31+
32+
### Run lint to check for problems
33+
34+
`cd samples/boundaries-click`
35+
`npx eslint index.ts`
36+
37+
## Feedback
38+
39+
For feedback related to this sample, please open a new issue on
40+
[GitHub](https://github.com/googlemaps-samples/js-api-samples/issues).
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<!doctype html>
2+
<!--
3+
@license
4+
Copyright 2025 Google LLC. All Rights Reserved.
5+
SPDX-License-Identifier: Apache-2.0
6+
-->
7+
<!-- [START maps_boundaries_click_event] -->
8+
<html>
9+
<head>
10+
<title>Handle Region Boundary Click Event</title>
11+
12+
<link rel="stylesheet" type="text/css" href="./style.css" />
13+
<script type="module" src="./index.js"></script>
14+
<!-- prettier-ignore -->
15+
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
16+
({key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script>
17+
</head>
18+
<body>
19+
<gmp-map center="39.23,-105.73" zoom="8" map-id="8b37d7206ccf0121a2634fd5">
20+
</body>
21+
</html>
22+
<!-- [END maps_boundaries_click_event] -->

samples/boundaries-click/index.ts

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
/**
2+
* @license
3+
* Copyright 2025 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
// [START maps_boundaries_click_event]
8+
let innerMap;
9+
let featureLayer;
10+
let infoWindow;
11+
let lastInteractedFeatureIds = [];
12+
let lastClickedFeatureIds = [];
13+
14+
// [START maps_boundaries_click_event_handler]
15+
function handleClick(/* MouseEvent */ e) {
16+
lastClickedFeatureIds = e.features.map((f) => f.placeId);
17+
lastInteractedFeatureIds = [];
18+
featureLayer.style = applyStyle;
19+
createInfoWindow(e);
20+
}
21+
22+
function handleMouseMove(/* MouseEvent */ e) {
23+
lastInteractedFeatureIds = e.features.map((f) => f.placeId);
24+
featureLayer.style = applyStyle;
25+
}
26+
// [END maps_boundaries_click_event_handler]
27+
28+
async function initMap() {
29+
// Request needed libraries.
30+
const { Map, InfoWindow } = (await google.maps.importLibrary(
31+
'maps'
32+
)) as google.maps.MapsLibrary;
33+
34+
// Get the gmp-map element.
35+
const mapElement = document.querySelector(
36+
'gmp-map'
37+
) as google.maps.MapElement;
38+
39+
// Get the inner map.
40+
innerMap = mapElement.innerMap;
41+
42+
// Set map options.
43+
innerMap.setOptions({
44+
mapTypeControl: false,
45+
});
46+
47+
//[START maps_boundaries_click_event_add_layer]
48+
// Add the feature layer.
49+
featureLayer = innerMap.getFeatureLayer(
50+
google.maps.FeatureType.ADMINISTRATIVE_AREA_LEVEL_2
51+
);
52+
53+
// Add the event listeners for the feature layer.
54+
featureLayer.addListener('click', handleClick);
55+
featureLayer.addListener('mousemove', handleMouseMove);
56+
57+
// Map event listener.
58+
innerMap.addListener('mousemove', () => {
59+
// If the map gets a mousemove, that means there are no feature layers
60+
// with listeners registered under the mouse, so we clear the last
61+
// interacted feature ids.
62+
if (lastInteractedFeatureIds?.length) {
63+
lastInteractedFeatureIds = [];
64+
featureLayer.style = applyStyle;
65+
}
66+
});
67+
//[END maps_boundaries_click_event_add_layer]
68+
69+
// Create the infowindow.
70+
infoWindow = new InfoWindow({});
71+
// Apply style on load, to enable clicking.
72+
featureLayer.style = applyStyle;
73+
}
74+
75+
// Helper function for the infowindow.
76+
async function createInfoWindow(event) {
77+
let feature = event.features[0];
78+
if (!feature.placeId) return;
79+
80+
// Update the info window.
81+
// Get the place instance from the selected feature.
82+
const place = await feature.fetchPlace();
83+
84+
// Create a new div to hold the text content.
85+
let content = document.createElement('div');
86+
87+
// Get the text values.
88+
let nameText = document.createElement('span');
89+
nameText.textContent = `Display name: ${place.displayName}`;
90+
let placeIdText = document.createElement('span');
91+
placeIdText.textContent = `Place ID: ${feature.placeId}`;
92+
let featureTypeText = document.createElement('span');
93+
featureTypeText.textContent = `Feature type: ${feature.featureType}`;
94+
95+
// Append the text to the div.
96+
content.appendChild(nameText);
97+
content.appendChild(document.createElement('br'));
98+
content.appendChild(placeIdText);
99+
content.appendChild(document.createElement('br'));
100+
content.appendChild(featureTypeText);
101+
102+
updateInfoWindow(content, event.latLng);
103+
}
104+
105+
// [START maps_boundaries_click_event_style]
106+
// Define styles.
107+
// Stroke and fill with minimum opacity value.
108+
const styleDefault = {
109+
strokeColor: '#810FCB',
110+
strokeOpacity: 1.0,
111+
strokeWeight: 2.0,
112+
fillColor: 'white',
113+
fillOpacity: 0.1, // Polygons must be visible to receive events.
114+
};
115+
// Style for the clicked polygon.
116+
const styleClicked = {
117+
...styleDefault,
118+
fillColor: '#810FCB',
119+
fillOpacity: 0.5,
120+
};
121+
// Style for polygon on mouse move.
122+
const styleMouseMove = {
123+
...styleDefault,
124+
strokeWeight: 4.0,
125+
};
126+
127+
// Apply styles using a feature style function.
128+
function applyStyle(/* FeatureStyleFunctionOptions */ params) {
129+
const placeId = params.feature.placeId;
130+
//@ts-ignore
131+
if (lastClickedFeatureIds.includes(placeId)) {
132+
return styleClicked;
133+
}
134+
//@ts-ignore
135+
if (lastInteractedFeatureIds.includes(placeId)) {
136+
return styleMouseMove;
137+
}
138+
return styleDefault;
139+
}
140+
// [END maps_boundaries_click_event_style]
141+
142+
// Helper function to create an info window.
143+
function updateInfoWindow(content, center) {
144+
infoWindow.setContent(content);
145+
infoWindow.setPosition(center);
146+
infoWindow.open({
147+
map: innerMap,
148+
shouldFocus: false,
149+
});
150+
}
151+
152+
initMap();
153+
// [END maps_boundaries_click_event]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "@js-api-samples/boundaries-click",
3+
"version": "1.0.0",
4+
"scripts": {
5+
"build": "tsc && bash ../jsfiddle.sh boundaries-click && bash ../app.sh boundaries-click && bash ../docs.sh boundaries-click && npm run build:vite --workspace=. && bash ../dist.sh boundaries-click",
6+
"test": "tsc && npm run build:vite --workspace=.",
7+
"start": "tsc && vite build --base './' && vite",
8+
"build:vite": "vite build --base './'",
9+
"preview": "vite preview"
10+
},
11+
"dependencies": {
12+
13+
}
14+
}

samples/boundaries-click/style.css

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @license
3+
* Copyright 2025 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
/* [START maps_boundaries_click_event] */
7+
/*
8+
* Always set the map height explicitly to define the size of the div element
9+
* that contains the map.
10+
*/
11+
gmp-map {
12+
height: 100%;
13+
}
14+
15+
/*
16+
* Optional: Makes the sample page fill the window.
17+
*/
18+
html,
19+
body {
20+
height: 100%;
21+
margin: 0;
22+
padding: 0;
23+
}
24+
25+
/* [END maps_boundaries_click_event] */
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"compilerOptions": {
3+
"module": "esnext",
4+
"target": "esnext",
5+
"strict": true,
6+
"noImplicitAny": false,
7+
"lib": [
8+
"es2015",
9+
"esnext",
10+
"es6",
11+
"dom",
12+
"dom.iterable"
13+
],
14+
"moduleResolution": "Node",
15+
"jsx": "preserve"
16+
}
17+
}

0 commit comments

Comments
 (0)