This repository has been archived by the owner on May 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 127
/
Select Pushpins within an Isochrone.html
232 lines (184 loc) · 9.38 KB
/
Select Pushpins within an Isochrone.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
<!DOCTYPE html>
<html lang="en">
<head>
<title>Select Pushpins within an Isochrone - Bing Maps 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 retrieve an isochrone (drive time polygon) from the Bing Maps REST services, and then filter the pushpins on the map that are within the isochrone." />
<meta name="keywords" content="Microsoft maps, map, gis, API, SDK, Bing, Bing Maps" />
<meta name="author" content="Microsoft Bing Maps" />
<meta name="screenshot" content="screenshot.jpg" />
<script>
var map, searchArea, pinLayer, url;
function GetMap() {
map = new Microsoft.Maps.Map('#myMap', {
center: new Microsoft.Maps.Location(47.614907, -122.193876),
zoom: 11
});
//Add some random pushpins to a layer on the map.
pinLayer = new Microsoft.Maps.Layer();
map.layers.insert(pinLayer);
var pushpins = Microsoft.Maps.TestDataGenerator.getPushpins(100, map.getBounds(), { color: 'purple' });
pinLayer.add(pushpins);
//Load the Spatial Math module.
Microsoft.Maps.loadModule('Microsoft.Maps.SpatialMath');
}
function isochroneSearch() {
//Show the loading icon.
document.getElementById('loadingIcon').style.display = '';
//Remove previous search area and set pushpin states back to normal.
if (searchArea) {
map.entities.remove(searchArea);
}
//Get all the pushpins from the pinLayer.
var pins = pinLayer.getPrimitives();
//Clear any previously selected data.
for (var i = 0; i < pins.length; i++) {
pins[i].setOptions({ color: 'purple' });
}
//Create the REST isochrone query URL.
url = 'https://dev.virtualearth.net/REST/v1/Routes/Isochrones?&optimize=time&travelMode=driving';
//Use the center of the map as the waypoint for the isochrone.
var center = map.getCenter();
url += '&waypoint=' + center.latitude + ',' + center.longitude;
//Set the max time parameter for the isochrone query in minutes.
url += '&timeUnit=minute&maxTime=' + document.getElementById('driveTime').value;
//Add key to query for authenication.
url += '&key=';
map.getCredentials(getIsochrone);
}
function getIsochrone(sessionKey) {
url += sessionKey;
callRestServiceCORS(url, function (data) {
//Hide loading icon.
document.getElementById('loadingIcon').style.display = 'none';
//Parse the REST response into polygon objects.
searchArea = getIsochronePolygons(data);
if (searchArea) {
//Find all intersection pushpins in the search area polygon.
var selectedPins = findIntersectingData(searchArea);
//Do something with the selected pushpins.
//Add the isochrone polygon to the map for visualization.
map.entities.push(searchArea);
} else {
alert('Unable to generate isochrone.');
}
}, function (error) {
alert('An error occured when requesting the isochrone.');
//Hide loading icon.
document.getElementById('loadingIcon').style.display = 'none';
});
}
function getIsochronePolygons(data) {
if (data &&
data.resourceSets &&
data.resourceSets.length > 0 &&
data.resourceSets[0].resources &&
data.resourceSets[0].resources.length > 0 &&
data.resourceSets[0].resources[0].polygons) {
var polyData = data.resourceSets[0].resources[0].polygons;
var polygons = [];
for (var i = 0; i < polyData.length; i++) {
var rings = [];
for (var j = 0; j < polyData[i].coordinates.length; j++) {
var ring = [];
for (var k = 0; k < polyData[i].coordinates[j].length; k++) {
ring.push(new Microsoft.Maps.Location(polyData[i].coordinates[j][k][0], polyData[i].coordinates[j][k][1]));
}
//Need atleast 3 locations in a ring to create a polygon.
if (ring.length >= 3) {
rings.push(ring);
}
}
if (rings.length > 0) {
polygons.push(new Microsoft.Maps.Polygon(rings));
}
}
if (polygons.length > 0) {
return polygons;
}
}
return null;
}
//Find all pushpins on the map that intersect with the search area.
function findIntersectingData(searchArea) {
if (searchArea) {
//Get all the pushpins from the pinLayer.
var pins = pinLayer.getPrimitives();
//Using spatial math find all pushpins that intersect with the drawn search area.
//The returned data is a copy of the intersecting data and not a reference to the original shapes,
//so making edits to them will not cause any updates on the map.
var intersectingPins = Microsoft.Maps.SpatialMath.Geometry.intersection(pins, searchArea);
//The data returned by the intersection function can be null, a single shape, or an array of shapes.
if (intersectingPins) {
//For ease of usem wrap individudal shapes in an array.
if (intersectingPins && !(intersectingPins instanceof Array)) {
intersectingPins = [intersectingPins];
}
var selectedPins = [];
//Loop through and map the intersecting pushpins back to their original pushpins by comparing their coordinates.
for (var j = 0; j < intersectingPins.length; j++) {
for (var i = 0; i < pins.length; i++) {
if (Microsoft.Maps.Location.areEqual(pins[i].getLocation(), intersectingPins[j].getLocation())) {
//Set the selected pin color to red.
pins[i].setOptions({ color: 'red' });
selectedPins.push(pins[i]);
break;
}
}
}
//Return the pushpins that were selected.
return selectedPins;
}
}
return null;
}
function callRestServiceCORS(requestUrl, callback, errorCallback) {
if (callback) {
var http = new XMLHttpRequest();
http.open("GET", requestUrl, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
//Request was successful, do something with it.
var result = JSON.parse(http.responseText);
callback(result);
}
}
http.onerror = errorCallback;
http.send();
}
}
</script>
</head>
<body>
<div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;background-color:gray"></div>
<img id="loadingIcon" src="/images/loadingIcon.gif" style="position:absolute;top:250px;left:350px;display:none;" />
<br />
Drive Time:
<select id="driveTime">
<option value="10" selected="selected">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
</select> minutes
<input type="button" value="Isochrone Search" onclick="isochroneSearch()" />
<fieldset style="width:800px;margin-top:10px;">
<legend>Select Pushpins within an Isochrone Sample</legend>
This sample shows how to retrieve an isochrone (drive time polygon) from the Bing Maps REST services, and then filter the pushpins on the map that are within the isochrone.
This is useful when trying performs queries like "Which locations are within 15 minutes of here.".
For simplicity, this sample uses the center of the map as the isochrone starting waypoint.
</fieldset>
<script>
// Dynamic load the Bing Maps Key and Script
// Get your own Bing Maps key at https://www.microsoft.com/maps
(async () => {
let script = document.createElement("script");
let bingKey = await fetch("https://samples.azuremaps.com/api/GetBingMapsKey").then(r => r.text()).then(key => { return key });
script.setAttribute("src", `https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=${bingKey}`);
document.body.appendChild(script);
})();
</script>
</body>
</html>