-
Notifications
You must be signed in to change notification settings - Fork 451
/
Search for boundaries.html
321 lines (254 loc) · 13.8 KB
/
Search for boundaries.html
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<!DOCTYPE html>
<html lang="en">
<head>
<title>Search for boundaries - Azure Maps Web SDK Samples</title>
<meta charset="utf-8" />
<link rel="shortcut icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="This sample shows how to use the Services module for Azure Maps to search for locations that have boundaries and display them on the map. Azure Maps provides boundary data for administrative areas such as states, countries, cities, postal codes, and other boundaries such as industrial areas." />
<meta name="keywords" content="Microsoft maps, map, gis, API, SDK, services, module, geolocation, search, geocode, geocoding, adminstrative boundaries, boundary, boundaries, polygon" />
<meta name="author" content="Microsoft Azure Maps" />
<meta name="version" content="1.0" />
<meta name="screenshot" content="screenshot.jpg" />
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" rel="stylesheet" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
<!-- Add a reference to the Azure Maps Rest Helper JavaScript file. -->
<script src="https://samples.azuremaps.com/lib/azure-maps/azure-maps-helper.min.js"></script>
<script>
var map, datasource, layer, popup, displayedLocation;
// Your Azure Maps client id for accessing your Azure Maps account.
var azureMapsClientId = 'e6b6ab59-eb5d-4d25-aa57-581135b927f0';
// URL to your authentication service that retrieves an Microsoft Entra ID Token.
var tokenServiceUrl = 'https://samples.azuremaps.com/api/GetAzureMapsToken';
// URL for the Azure Maps Search Geocoder API.
var geocodeUrl = 'https://{azMapsDomain}/geocode?api-version=2023-06-01&top=10&view=Auto&query={query}';
// URL for the Azure Maps Search Polygon API.
var polygonUrl = 'https://{azMapsDomain}/search/polygon?api-version=2023-06-01&coordinates={coordinates}&view=Auto&resultType={resultType}&resolution={resolution}';
//A list of entity types that the boundary service supports.
var boundaryEntityTypes = ['adminDistrict', 'adminDistrict2', 'countryRegion', 'locality', 'neighborhood', 'postalCode', 'postalCode2', 'postalCode3', 'postalCode4'];
//A simple local-cache to store information about boundaries for this sample.
// Format: { id: { position: [], entityType: '', bbox: [] } } where the id is a pipe delimited formatted address and entity type since many places could have the same formatted address.
//Not caching boundary polygon for this sample as we want to be able to switch between resolutions.
var boundaryCache = {};
// Function to retrieve an Azure Maps access token.
function getToken(resolve, reject, map) {
fetch(tokenServiceUrl).then(response => {
if (response.ok) {
return response.text();
}
throw new Error('Failed to retrieve Azure Maps token.');
}).then(token => resolve(token)).catch(error => reject(error));
}
function getMap() {
// Initialize a map instance.
map = new atlas.Map('myMap', {
style: 'grayscale_light',
view: 'Auto',
// Add authentication details for connecting to Azure Maps.
authOptions: {
// Use Microsoft Entra ID authentication.
authType: 'anonymous',
clientId: azureMapsClientId,
getToken: getToken
// Alternatively, use an Azure Maps key.
// Get an Azure Maps key at https://azure.com/maps.
// NOTE: The primary key should be used as the key.
// authType: 'subscriptionKey',
// subscriptionKey: '[YOUR_AZURE_MAPS_KEY]'
}
});
// Wait until the map resources are ready.
map.events.add('ready', function () {
// Create a data source and add it to the map.
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
// Add a layers for rendering the boundaries as polygons.
layer = new atlas.layer.PolygonLayer(datasource, null, {
fillColor: 'hotpink'
});
map.layers.add(layer, 'labels');
// Create a popup but leave it closed so we can update it and display it later.
popup = new atlas.Popup();
// Add a click event to the layer.
map.events.add('click', layer, layerClicked);
});
}
function search() {
var query = document.getElementById('input').value;
// Remove any previous results from the map.
datasource.clear();
document.getElementById('resultList').innerHTML = '';
popup.close();
// Show the loading icon.
document.getElementById('loadingIcon').style.display = '';
// Search for locatoins.
var geocodeRequestUrl = geocodeUrl
.replace('{query}', encodeURIComponent(query));
processRequest(geocodeRequestUrl).then(fc => {
var r = fc.features;
var html = ['<h3>Results</h3><ol>'];
var hasBoundaries = false;
var firstResult;
// Loop through the results and extract the ones that might have boundaries.
for (var i = 0; i < r.length; i++) {
var t = r[i].properties.type;
//Convert the type property to a boundary Entity type value as it seems these values differ between services.
switch (t) {
case 'CountryRegion':
t = 'countryRegion';
break;
case 'AdminDivision1':
t = 'adminDistrict';
break;
case 'AdminDivision2':
t = 'adminDistrict2';
break;
case 'Postcode1':
t = 'postalCode';
break;
case 'Postcode2':
t = 'postalCode2';
break;
case 'Postcode3':
t = 'postalCode3';
break;
case 'Postcode4':
t = 'postalCode4';
break;
case 'PopulatedPlace':
t = 'locality';
break;
case 'Neighborhood':
t = 'neighborhood';
break;
}
//Check to see if the search result could have a boundary.
if (boundaryEntityTypes.indexOf(t) != -1) {
var id = `${r[i].properties.address.formattedAddress}|${t}`;
//Cache some basic information about the location.
boundaryCache[id] = {
position: r[i].geometry.coordinates,
entityType: t
};
if (!firstResult) {
firstResult = id;
}
// Create a link to select and zoom into the boundary.
html.push(`<li><a href="javascript:void(0)" onclick="getPolygon('${id}');">${r[i].properties.address.formattedAddress}</a> (${t}, Confidence: ${r[i].properties.confidence})</li>`);
hasBoundaries = true;
}
}
html.push('</ol>');
if (hasBoundaries) {
// Focus on the first polygon in the list.
getPolygon(firstResult);
// Display the list of results.
document.getElementById('resultList').innerHTML = html.join('');
// Hide the loading icon.
document.getElementById('loadingIcon').style.display = 'none';
} else {
document.getElementById('resultList').innerHTML = 'No boundary found.';
// Hide the loading icon.
document.getElementById('loadingIcon').style.display = 'none';
}
});
}
function getPolygon(id) {
popup.close();
//Make sure we have information in the cache for the provided ID.
if (boundaryCache[id]) {
displayedLocation = id;
var b = boundaryCache[id];
//Get the selected resolution type.
var resolution = document.getElementById('resolutionSelector').value;
//Retrieve the boundary from Azure Maps.
// Show the loading icon.
document.getElementById('loadingIcon').style.display = '';
// Retrieve the boudary polygons. The response may be large, so allow a longer abort time.
var polygonRequestUrl = polygonUrl
.replace('{coordinates}', b.position.join(','))
.replace('{resultType}', b.entityType)
.replace('{resolution}', resolution);
processRequest(polygonRequestUrl).then(f => {
console.log(`Response size for '${id}' boundary: ${Math.round(JSON.stringify(f).length / 1024 / 1024 * 100) / 100}MB`);
//Cache the boundary.
b.boundary = f;
//Add the boundary to the map.
datasource.setShapes(f);
//Caclaulte and cache the bounding box of the boundary.
b.bbox = atlas.data.BoundingBox.fromData(f);
//Update the map camera so that it focuses on the geometry.
map.setCamera({ bounds: b.bbox, padding: 40 });
// Hide the loading icon.
document.getElementById('loadingIcon').style.display = 'none';
}, e => {
//An error occurred, clear the data source.
alert('Unable to retrieve boundary for this location.');
datasource.clear();
// Hide the loading icon.
document.getElementById('loadingIcon').style.display = 'none';
});
}
}
function reloadBoundary() {
if (displayedLocation) {
getPolygon(displayedLocation);
}
}
function layerClicked(e) {
// Get the GeoJSON version of the feature.
var f = e.shapes[0].toJson();
// Calculate stats for the boundary.
var numPos = 0, numPolygons = 0, i, j;
if (f.geometry.type === 'Polygon') {
numPolygons = 1;
// Count the number of positions in the polygons.
for (i = 0; i < f.geometry.coordinates.length; i++) {
numPos += f.geometry.coordinates[i].length;
}
} else {
// Must by MultiPolygon
// Count the number of polygons in the MultiPolygon
numPolygons = f.geometry.coordinates.length;
// Count the number of positions in all the polygons.
for (i = 0; i < f.geometry.coordinates.length; i++) {
for (j = 0; j < f.geometry.coordinates[i].length; j++) {
numPos += f.geometry.coordinates[i][j].length;
}
}
}
// Set the popup options.
popup.setOptions({
// Update the content of the popup.
content: `<div style='padding:15px;'>Type: ${f.geometry.type}<br/># polygons: ${numPolygons.toLocaleString()}<br/># positions: ${numPos.toLocaleString()}</div>`,
// Place the popup where the user clicked.
position: e.position
});
// Open the popup.
popup.open(map);
}
</script>
</head>
<body onload="getMap()">
<div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;"></div>
<div style="position:absolute;top:15px;left:15px;background-color:white;padding:10px;border-radius:10px;">
<input type="text" id="input" value="London" />
<input type="button" onClick="search()" value="Search" />
Resolution:
<select id="resolutionSelector" onchange="reloadBoundary()">
<option value="small">Small</option>
<option value="medium" selected>Medium</option>
<option value="large">Large</option>
<option value="huge">Huge</option>
</select>
<div id="resultList"></div>
</div>
<img id="loadingIcon" src="/images/loadingIcon.gif" title="Loading" style="position:absolute;left:calc(50% - 25px);top:250px;display:none;" />
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
<legend>Search for boundaries</legend>
This sample shows how to use Azure Maps to search for locations that have boundaries and display them on the map.
Azure Maps provides boundary data for administrative areas such as states, countries, cities, postal codes, and other boundaries such as industrial areas.
</fieldset>
</body>
</html>