This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
/
Animate a Symbol along a Path.html
326 lines (263 loc) · 13.2 KB
/
Animate a Symbol along a Path.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
322
323
324
325
326
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animate a Symbol along a Path - Azure Maps Web SDK Samples</title>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="This sample shows how to animate a symbol along a path on the map smoothly. " />
<meta name="keywords" content="Microsoft maps, map, gis, API, SDK, animation, animate, animations, symbols, pushpins, markers, pins, line, linestring, polyline" />
<meta name="author" content="Microsoft Azure Maps" />
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
<script type='text/javascript'>
var map, pin, lineSource, pinSource;
var animationTime = 15000;
var animation;
//Create an array of points to define a path to animate along.
var path = [
[-122.34758, 47.62155],
[-122.34764, 47.61859],
[-122.33787, 47.61295],
[-122.34217, 47.60964]
];
function GetMap() {
//Point the Azure Maps domain to the US Azure Gov Cloud domain.
atlas.setDomain('atlas.azure.us');
//Initialize a map instance.
map = new atlas.Map('myMap', {
center: [-122.345, 47.615],
zoom: 14,
view: 'Auto',
//Add your Azure Maps subscription key to the map SDK. Get an Azure Maps key at https://azure.com/maps
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: '<Your Azure Maps Key>'
}
});
//Wait until the map resources are ready.
map.events.add('ready', function () {
//Load a custom image icon into the map resources.
map.imageSprite.add('arrow-icon', '../Common/images/icons/gpsArrowIcon.png').then(function () {
//Create data sources and add them to the map.
lineSource = new atlas.source.DataSource();
pinSource = new atlas.source.DataSource();
map.sources.add([lineSource, pinSource]);
//Create a layer to render the path.
map.layers.add(new atlas.layer.LineLayer(lineSource, null, {
strokeColor: 'DodgerBlue',
strokeWidth: 3
}));
//Create a line for the path and add it to the data source.
lineSource.add(new atlas.data.LineString(path));
//Create a layer to render a symbol which we will animate.
map.layers.add(new atlas.layer.SymbolLayer(pinSource, null, {
iconOptions: {
//Pass in the id of the custom icon that was loaded into the map resources.
image: 'arrow-icon',
//Anchor the icon to the center of the image.
anchor: 'center',
//Rotate the icon based on the rotation property on the point data.
rotation: ['get', 'rotation'],
//Have the rotation align with the map.
rotationAlignment: 'map',
//For smoother animation, ignore the placement of the icon. This skips the label collision calculations and allows the icon to overlap map labels.
ignorePlacement: true,
//For smoother animation, allow symbol to overlap all other symbols on the map.
allowOverlap: true
},
textOptions: {
//For smoother animation, ignore the placement of the text. This skips the label collision calculations and allows the text to overlap map labels.
ignorePlacement: true,
//For smoother animation, allow text to overlap all other symbols on the map.
allowOverlap: true
}
}));
//Create a pin and wrap with the shape class and add to data source.
pin = new atlas.Shape(new atlas.data.Feature(new atlas.data.Point(path[0]), {
rotation: 180
}));
pinSource.add(pin);
animation = new animations.PathAnimation(path, function (position, heading, progress) {
//Update the rotation of the symbol.
pin.setProperties({
rotation: heading
});
//Update the symbols coordinates.
pin.setCoordinates(position);
if (document.getElementById('followSymbol').checked) {
map.setCamera({
center: position,
bearing: heading,
pitch: 45,
zoom: 15,
type: "fly",
duration: 100
});
}
}, animationTime);
});
});
}
function play() {
if (animation) {
animation.play();
}
}
function pause() {
if (animation) {
animation.pause();
}
}
function stop() {
if (animation) {
animation.stop();
}
}
var animations = (function () {
var self = this;
var _delay = 30; //30 = 33.3 frames per second, 16 = 62.5 frames per second
this.PathAnimation = function (path, intervalCallback, duration) {
/// <summary>This class extends from the BaseAnimation class and cycles through a set of positions over a period of time, calculating mid-point positions along the way.</summary>
/// <param name="path" type="Position[]">An array of positions to cycle through.</param>
/// <param name="intervalCallback" type="Function">A function that is called when a frame is to be rendered. This callback function recieves three values; current position, heading, progress.</param>
/// <param name="duration" type="Number">Length of time in ms that the animation should run for. Default is 1000 ms.</param>
var _totalDistance = 0,
_intervalLocs = [path[0]],
_intervalHeadings = [],
_intervalIdx = [0],
_frameCount = Math.ceil(duration / _delay), idx;
var progress, dlat, dlon;
//Calcualte the total distance along the path in degrees.
for (var i = 0; i < path.length - 1; i++) {
dlat = (path[i + 1][1] - path[i][1]);
dlon = (path[i + 1][0] - path[i][0]);
_totalDistance += Math.sqrt(dlat * dlat + dlon * dlon);
}
//Pre-calculate step points for smoother rendering.
for (var f = 0; f < _frameCount; f++) {
progress = (f * _delay) / duration;
var travel = progress * _totalDistance;
var alpha;
var dist = 0;
var dx = travel;
for (var i = 0; i < path.length - 1; i++) {
dlat = (path[i + 1][1] - path[i][1]);
dlon = (path[i + 1][0] - path[i][0]);
alpha = Math.atan2(dlat * Math.PI / 180, dlon * Math.PI / 180);
dist += Math.sqrt(dlat * dlat + dlon * dlon);
if (dist >= travel) {
idx = i;
break;
}
dx = travel - dist;
}
if (dx != 0 && idx < path.length - 1) {
dlat = dx * Math.sin(alpha);
dlon = dx * Math.cos(alpha);
var dest = [path[idx][0] + dlon, path[idx][1] + dlat];
_intervalLocs.push(dest);
_intervalHeadings.push(atlas.math.getHeading(path[idx], dest));
_intervalIdx.push(idx);
}
}
//Ensure the last location is the last position in the path.
_intervalHeadings.push(atlas.math.getHeading(_intervalLocs[_intervalLocs.length - 1], path[path.length - 1]));
_intervalLocs.push(path[path.length - 1]);
_intervalIdx.push(path.length - 1);
if (_intervalHeadings.length < _intervalLocs.length) {
_intervalHeadings.push(_intervalHeadings[_intervalHeadings.length - 1]);
}
return new self.BaseAnimation(
function (progress, frameIdx) {
if (intervalCallback) {
intervalCallback(_intervalLocs[frameIdx], _intervalHeadings[frameIdx], progress);
}
}, duration);
}
this.BaseAnimation = function (renderFrameCallback, duration) {
/// <summary>A base class that can be used to create animations that support play, pause and stop.</summary>
/// <param name="renderFrameCallback" type="Function">A function that is called when a frame is to be rendered. This function recieves two values; progress and frameIdx.</param>
/// <param name="duration" type="Number">Length of time in ms that the animation should run for. Default is 1000 ms.</param>
var _timerId,
frameIdx = 0,
_isPaused = true;
//Varify value
duration = (duration && duration > 0) ? duration : 1000;
this.play = function () {
if (renderFrameCallback) {
_isPaused = false;
if (!_timerId) {
let _startTime = performance.now() - frameIdx * _delay;
const callback = function (timestamp) {
if (!_isPaused) {
var progress = (timestamp - _startTime) / duration;
frameIdx = Math.max(0, Math.round((timestamp - _startTime) / _delay));
renderFrameCallback(progress, frameIdx);
if (progress >= 1) {
reset();
}
_timerId = requestAnimationFrame(callback);
} else {
_timerId = null;
}
}
_timerId = requestAnimationFrame(callback);
}
}
};
this.isPlaying = function () {
return !_isPaused;
};
this.pause = function () {
_isPaused = true;
};
this.stop = function () {
reset();
};
function reset() {
if (_timerId != null) {
clearInterval(_timerId);
_timerId = null;
}
frameIdx = 0;
renderFrameCallback(0, frameIdx);
_isPaused = true;
}
}
return self;
})();
</script>
<style>
#myMap {
position: relative;
width: 100%;
min-width: 290px;
height: 600px;
}
.controlPanel {
position: absolute;
top: 15px;
left: 15px;
border-radius: 5px;
padding: 5px;
background-color: white;
}
</style>
</head>
<body onload="GetMap()">
<div id="myMap"></div>
<div class="controlPanel">
<input type="button" value="Play" onclick="play()" />
<input type="button" value="Pause" onclick="pause()" />
<input type="button" value="Stop" onclick="stop()" />
<br />
Follow: <input id="followSymbol" type="checkbox" />
</div>
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
<legend><h1 style="font-size:16px">Animate a Symbol along a Path</h1></legend>
This sample shows how to animate a symbol along a path on the map smoothly.
</fieldset>
</body>
</html>