-
Notifications
You must be signed in to change notification settings - Fork 445
/
Calculate nearest locations.html
272 lines (224 loc) · 12.3 KB
/
Calculate nearest locations.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
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calculate nearest locations - 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 do a spatial join between two sets of points based on the shortest stright line distance or travel time along roads using the route matrix service." />
<meta name="keywords" content="Microsoft maps, map, gis, API, SDK, spatial analysis, spatial join, fire, school, route matrix, matrix, distance matrix, travel time" />
<meta name="author" content="Microsoft Azure Maps" />
<meta name="version" content="2.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, schoolSource, lineSource, fireStationSource, schools, fireStations, travelTimeMatrix;
// 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 making async calls to the route matrix service.
var routeMatrixAsyncUrl = 'https://{azMapsDomain}/route/matrix/json?api-version=1.0';
// 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', {
center: [-105.076, 40.56],
zoom: 11,
style: 'grayscale_dark',
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 () {
// Load the custom image icon into the map resources.
map.imageSprite.add('fire-shield-icon', '/images/icons/fire_shield.png');
// Download school and fire station location GeoJSON data.
Promise.all([
fetch('/data/geojson/fort_collins_schools.json').then(response => response.json()),
fetch('/data/geojson/fort_collins_fire_stations.json').then(response => response.json())
]).then(results => {
schools = results[0].features;
fireStations = results[1].features;
// Create a data source for shortest paths between schools and fire stations.
lineSource = new atlas.source.DataSource();
map.sources.add(lineSource);
// Create a data source for schools.
schoolSource = new atlas.source.DataSource();
map.sources.add(schoolSource);
schoolSource.add(schools);
// Create a data source for fire stations.
fireStationSource = new atlas.source.DataSource();
map.sources.add(fireStationSource);
fireStationSource.add(fireStations);
// Add rendering layers below labels.
map.layers.add([
// Render the shortest paths between the schools and fire stations.
new atlas.layer.LineLayer(lineSource, null, {
// Clore the line differently based on the first station ID.
strokeColor: [
'match',
['get', 'stationId'],
4, '#8dd3c7',
6, '#fdb462',
8, '#b3de69',
10, '#fccde5',
12, '#d9d9d9',
14, '#bc80bd',
16, '#ccebc5',
18, '#ffed6f',
20, '#f8ece8',
22, '#ffffb3',
24, '#bebada',
26, '#fb8072',
28, '#80b1d3',
'black'
],
strokeWidth: 2
}),
// Render each address as a colored circle based on nearest fire station.
new atlas.layer.BubbleLayer(schoolSource, null, {
createIndicators: true, // to enable bubble layer a11y feature
radius: 4,
strokeWidth: 0
})
], 'labels');
// Render an icon for each fire station.
map.layers.add(new atlas.layer.SymbolLayer(fireStationSource, null, {
iconOptions: {
image: 'fire-shield-icon',
size: 0.5,
anchor: "center",
allowOverlap: true,
ignorePlacement: true
},
textOptions: {
textField: ['id'],
color: 'white',
size: 12,
offset: [0, 0.4],
allowOverlap: true,
ignorePlacement: true
}
}));
});
});
}
function analyzeStraightLines() {
var lines = [];
for (var i = 0, len = schools.length; i < len; i++) {
var s = schools[i];
var minDistance = Infinity;
var minStation;
fireStations.forEach(fs => {
// Calculate the stright line distance to each fire station and find the closest one to the address.
var d = atlas.math.getDistanceTo(s.geometry, fs.geometry);
if (d < minDistance) {
minDistance = d;
minStation = fs;
}
});
lines.push(new atlas.data.Feature(new atlas.data.LineString([s.geometry.coordinates, minStation.geometry.coordinates]), {
stationId: minStation.id
}));
}
lineSource.setShapes(lines);
}
async function analyzeAlongRoads(metric) {
if (travelTimeMatrix) {
showTravelMetric(metric);
} else {
// Show loading icon.
document.getElementById('loadingIcon').style.display = '';
lineSource.clear();
// Create the request body to get a route matrix
var jsonBody = {
origins: {
type: 'MultiPoint',
coordinates: fireStations.map(fs => { return fs.geometry.coordinates })
},
destinations: {
type: 'MultiPoint',
coordinates: schools.map(a => { return a.geometry.coordinates })
}
};
// Initiate an async route matrix request.
var res = await processPostRequest(routeMatrixAsyncUrl, JSON.stringify(jsonBody));
// Get the status URL from the "location" response header.
var batchStatusUrl = res.headers.get('location');
// Initiate an async request to get the route matrix status response.
var res2 = await processRequest(batchStatusUrl);
// Cache the matrix so it is only calculated once.
travelTimeMatrix = res2.matrix;
// Show the shortest travel metric.
showTravelMetric(metric);
// Hide loading icon.
document.getElementById('loadingIcon').style.display = 'none';
}
}
// Function to show the shortest travel metric.
function showTravelMetric(metric) {
var lines = [];
var prop = (metric === 'time') ? 'travelTimeInSeconds' : 'lengthInMeters';
// Loop through each schools can calculate the shortest path.
for (var i = 0, len = schools.length; i < len; i++) {
var minMetric = Infinity;
var minStation;
// Loop through each fire station and find which one is the shortest travel time or distance away from the address.
for (var j = 0, cnt = fireStations.length; j < cnt; j++) {
// Get the travel time or distance for the schools/fire station pair.
var m = travelTimeMatrix[j][i].response.routeSummary[prop];
if (m < minMetric) {
minMetric = m;
minStation = fireStations[j];
}
}
lines.push(new atlas.data.Feature(new atlas.data.LineString([schools[i].geometry.coordinates, minStation.geometry.coordinates]), {
stationId: minStation.id
}));
}
lineSource.setShapes(lines);
}
</script>
</head>
<body onload="getMap()">
<div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;"></div>
<div style="position:absolute;top:10px;left:10px;background-color:#fff;padding:10px;border-radius:5px;">
Match closest by: <br /><br />
<input type="button" value="Straight line distances" onclick="analyzeStraightLines()" /><br /><br />
<input type="button" value="Travel time along roads" onclick="analyzeAlongRoads('time')" /><br /><br />
<input type="button" value="Travel distance along roads" onclick="analyzeAlongRoads('distance')" />
</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>Calculate nearest locations</legend>
This sample shows how to do a spatial join between two sets of points based on the shortest stright line distance or travel time along roads using the route matrix service.
In this case, the origins are fire stations, and the destinations are schools (blue dots). This analysis shows us which fire station is closest to which school.
A straight line distance is a fast and simple calculation, however, in many cases travel time is more important than a straight line distance.
With the Azure Maps route matrix service, additional route options can be specified, such as the travel mode, future travel times, vehicle dimensions, and much more.
</fieldset>
</body>
</html>