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
/
Fully Custom Drawing Toolbar.html
557 lines (459 loc) · 19.2 KB
/
Fully Custom Drawing Toolbar.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fully Custom Drawing Toolbar - 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="Create your own fully custom drawing toolbar and controls." />
<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;
var tools;
var drawingLayer;
var currentShape;
var currentMode;
var events = [];
var style = {
color: 'purple',
fillColor: 'rgba(0,255,0,0.5)',
strokeColor: 'blue',
strokeThickness: 3
};
function GetMap() {
map = new Microsoft.Maps.Map('#myMap', {});
//Load the DrawingTools and SpatialMath modules.
Microsoft.Maps.loadModule(['Microsoft.Maps.DrawingTools', 'Microsoft.Maps.SpatialMath'], function () {
//Create a layer for the drawn shapes.
drawingLayer = new Microsoft.Maps.Layer();
map.layers.insert(drawingLayer);
//Create an instance of the DrawingTools class and bind it to the map.
tools = new Microsoft.Maps.DrawingTools(map);
});
//When the user presses 'esc', take the polygon out of edit mode and re-add to base map.
document.getElementById('myMap').onkeypress = function (e) {
if (e.charCode === 27) {
setMode(null);
}
};
}
function setDrawingMode(mode, elm) {
clearSelection('DrawingModes', 'editButton');
elm.className = 'selectedEditButton';
switch (mode) {
case 'pushpin':
drawPushpin();
break;
case 'polyline':
drawPolyline();
break;
case 'polygon':
drawPolygon();
break;
case 'circle':
drawCircle();
break;
case 'rectangle':
drawRectangle();
break;
case 'edit':
edit();
break;
case 'erase':
erase();
break;
default:
break;
}
}
function drawPushpin() {
if (setMode('pushpin')) {
//Add a click event to the map to add pushpins.
events.push(Microsoft.Maps.Events.addHandler(map, 'click', function (e) {
currentShape = new Microsoft.Maps.Pushpin(e.location, {
color: style.color
});
drawingLayer.add(currentShape);
}));
}
}
function drawPolyline() {
if (setMode('polyline')) {
//Create a new polyline.
tools.create(Microsoft.Maps.DrawingTools.ShapeType.polyline, function (s) {
s.setOptions(style);
currentShape = s;
});
}
}
function drawPolygon() {
if (setMode('polygon')){
//Create a new polygon.
tools.create(Microsoft.Maps.DrawingTools.ShapeType.polygon, function (s) {
s.setOptions(style);
currentShape = s;
});
}
}
function drawCircle() {
if (setMode('circle')) {
var isMouseDown = false;
events.push(Microsoft.Maps.Events.addHandler(map, 'mousedown', function (e) {
//Lock map so it doesn't move when dragging.
map.setOptions({ disablePanning: true });
//Create a polygon for the circle.
currentShape = new Microsoft.Maps.Polygon([e.location, e.location, e.location], style);
//Store the center point in the polygons metadata.
currentShape.metadata = {
type: 'circle',
center: e.location
};
drawingLayer.add(currentShape);
isMouseDown = true;
}));
events.push(Microsoft.Maps.Events.addHandler(map, 'mousemove', function (e) {
if (isMouseDown) {
scaleCircle(e);
}
}));
events.push(Microsoft.Maps.Events.addHandler(map, 'mouseup', function (e) {
scaleCircle(e);
//Unlock map panning.
map.setOptions({ disablePanning: false });
isMouseDown = false;
}));
}
}
function scaleCircle(e) {
if (currentShape && currentShape.metadata && currentShape.metadata.type === 'circle') {
//Calculate distance from circle center to mouse.
var radius = Microsoft.Maps.SpatialMath.getDistanceTo(currentShape.metadata.center, e.location);
//Calculate circle locations.
var locs = Microsoft.Maps.SpatialMath.getRegularPolygon(currentShape.metadata.center, radius, 100);
currentShape.metadata.radius = radius;
//Update the circles location.
currentShape.setLocations(locs);
}
}
function editCircle(e) {
//Lock map so it doesn't move when dragging.
map.setOptions({ disablePanning: true });
var circle = e.primitive;
var distanceCenter = Microsoft.Maps.SpatialMath.getDistanceTo(e.location, circle.metadata.center);
var radius = Microsoft.Maps.SpatialMath.getDistanceTo(circle.metadata.center, circle.getLocations()[0]);
//If the initial location is closer to the center of the circle, move it, otherwise scale it.
if (distanceCenter < (radius - distanceCenter)) {
events.push(Microsoft.Maps.Events.addHandler(map, 'mousemove', function (e) {
currentShape.metadata.center = e.location;
var locs = Microsoft.Maps.SpatialMath.getRegularPolygon(currentShape.metadata.center, radius, 100);
currentShape.setLocations(locs);
}));
events.push(Microsoft.Maps.Events.addHandler(map, 'mouseup', function (e) {
currentShape.metadata.center = e.location;
var locs = Microsoft.Maps.SpatialMath.getRegularPolygon(currentShape.metadata.center, radius, 100);
currentShape.setLocations(locs);
//Unlock map panning.
map.setOptions({ disablePanning: false });
//Remove all events except the first one.
for (var i = 1; i < events.length; i++) {
Microsoft.Maps.Events.removeHandler(events[i]);
}
}));
} else {
events.push(Microsoft.Maps.Events.addHandler(map, 'mousemove', function (e) {
scaleCircle(e);
}));
events.push(Microsoft.Maps.Events.addHandler(map, 'mouseup', function (e) {
scaleCircle(e);
//Unlock map panning.
map.setOptions({ disablePanning: false });
//Remove all events except the first one.
for (var i = 1; i < events.length; i++) {
Microsoft.Maps.Events.removeHandler(events[i]);
}
}));
}
}
function drawRectangle() {
if (setMode('rectangle')) {
var isMouseDown = false;
events.push(Microsoft.Maps.Events.addHandler(map, 'mousedown', function (e) {
//Lock map so it doesn't move when dragging.
map.setOptions({ disablePanning: true });
//Create a polygon for the circle.
currentShape = new Microsoft.Maps.Polygon([e.location, e.location, e.location], style);
//Store the center point in the polygons metadata.
currentShape.metadata = {
type: 'rectangle'
};
drawingLayer.add(currentShape);
isMouseDown = true;
}));
events.push(Microsoft.Maps.Events.addHandler(map, 'mousemove', function (e) {
if (isMouseDown) {
updateRectangle(e);
}
}));
events.push(Microsoft.Maps.Events.addHandler(map, 'mouseup', function (e) {
updateRectangle(e);
//Unlock map panning.
map.setOptions({ disablePanning: false });
isMouseDown = false;
}));
}
}
function editRectangle(e) {
//Find the closest rectangle corner to the specified location and update that index.
var locIdx = 0;
var locs = currentShape.getLocations();
var rectangle = e.primitive;
var minDistance = Microsoft.Maps.SpatialMath.getDistanceTo(e.location, locs[0]);
var tempDistance;
for (var i = 1; i < locs.length; i++) {
tempDistance = Microsoft.Maps.SpatialMath.getDistanceTo(e.location, locs[i]);
if (tempDistance < minDistance) {
minDistance = tempDistance;
locIdx = i;
}
}
//Lock map panning.
map.setOptions({ disablePanning: true });
events.push(Microsoft.Maps.Events.addHandler(map, 'mousemove', function (e) {
updateRectangle(e, locIdx);
}));
events.push(Microsoft.Maps.Events.addHandler(map, 'mouseup', function (e) {
updateRectangle(e, locIdx);
//Unlock map panning.
map.setOptions({ disablePanning: false });
//Remove all events except the first one.
for (var i = 1; i < events.length; i++) {
Microsoft.Maps.Events.removeHandler(events[i]);
}
}));
}
function updateRectangle(e, firstCornerIdx) {
if (typeof firstCornerIdx === 'undefined') {
firstCornerIdx = 2;
}
if (currentShape && currentShape.metadata && currentShape.metadata.type === 'rectangle') {
//Get the first corner of the rectangle.
var locs = currentShape.getLocations();
var secondIdx = (firstCornerIdx + 1) % 4;
var thirdCornerIdx = (firstCornerIdx + 2) % 4;
var fourthCornerIdx = (firstCornerIdx + 3) % 4;
//Update the opposite corner of the rectangle.
locs[firstCornerIdx] = e.location;
//Calculate the other 3 corners of the rectanle.
locs[secondIdx] = new Microsoft.Maps.Location(locs[thirdCornerIdx].latitude, locs[firstCornerIdx].longitude);
locs[fourthCornerIdx] = new Microsoft.Maps.Location(locs[firstCornerIdx].latitude, locs[thirdCornerIdx].longitude);
if (locs.length == 5) {
locs[4] = locs[0];
}
currentShape.setLocations(locs);
}
}
function edit() {
if (setMode('edit')) {
//Enable pushpin dragging in layer.
setPushpinDraggability(true);
events.push(Microsoft.Maps.Events.addHandler(drawingLayer, 'mousedown', function (e) {
resetDrawingState();
currentShape = e.primitive;
if (e.primitive.metadata && e.primitive.metadata.type === 'circle') {
editCircle(e);
} else if (e.primitive.metadata && e.primitive.metadata.type === 'rectangle') {
editRectangle(e);
} else if (e.primitive instanceof Microsoft.Maps.Polyline || e.primitive instanceof Microsoft.Maps.Polygon) {
//Remove the shape from the map as the drawing tools will display it in the drawing layer.
drawingLayer.remove(e.primitive);
//Pass the shape to the drawing tools to be edited.
tools.edit(e.primitive);
}
}));
} else {
//Disable pushpin dragging in layer.
setPushpinDraggability(false);
}
}
function erase() {
if (setMode('erase')) {
events.push(Microsoft.Maps.Events.addHandler(drawingLayer, 'mousedown', function (e) {
drawingLayer.remove(e.primitive);
}));
}
}
//Sets the drawing mode, or toggles out of a mode if it is already set.
//Returns true if the specified mode is new.
function setMode(mode) {
//Remove all attached events.
for(var i=0; i < events.length;i++){
Microsoft.Maps.Events.removeHandler(events[i]);
}
events = [];
//Unlock map so incase it has been locked previously.
map.setOptions({ disablePanning: true });
var state = false;
if (currentMode === mode || mode == null) {
//Toggle out of currentMode mode.
currentMode = null;
clearSelection('DrawingModes', 'editButton');
} else {
currentMode = mode;
state = true;
}
resetDrawingState();
return state;
}
function resetDrawingState() {
//Stop any current drawing.
if (currentShape) {
tools.finish(function (s) {
//Add the completed shape to the drawing layer.
drawingLayer.add(s);
});
currentShape = null;
}
if(currentMode !== 'edit') {
//Disable pushpin dragging in layer.
setPushpinDraggability(false);
}
}
function setPushpinDraggability(draggable) {
var shapes = drawingLayer.getPrimitives();
for (var i = 0, len = shapes.length; i < len; i++) {
if (shapes[i] instanceof Microsoft.Maps.Pushpin) {
shapes[i].setOptions({ draggable: draggable });
}
}
}
function setPushpinColor(elm) {
clearSelection('PushpinColors', 'colorBox');
elm.className = 'selectedColorBox';
style.color = elm.style.backgroundColor;
updateShapeStyle();
}
function setFillColor(elm) {
clearSelection('FillColors', 'colorBox');
elm.className = 'selectedColorBox';
style.fillColor = elm.style.backgroundColor;
updateShapeStyle();
}
function setStrokeColor(elm) {
clearSelection('StrokeColors', 'colorBox');
elm.className = 'selectedColorBox';
style.strokeColor = elm.style.backgroundColor;
updateShapeStyle();
}
function setStrokeThickness(thickness) {
style.strokeThickness = thickness;
updateShapeStyle();
}
function updateShapeStyle() {
if (currentShape) {
currentShape.setOptions(style);
//If the shape is a poly type it may be in edit mode, take it out, update and put it back in.
if (currentShape instanceof Microsoft.Maps.Polyline || currentShape instanceof Microsoft.Maps.Polygon) {
tools.finish(function (s) {
s.setOptions(style);
tools.edit(s);
});
}
}
}
//Removes the selected state for the style options.
function clearSelection(parentId, className) {
var parent = document.getElementById(parentId);
for (var i = 0; i < parent.children.length; i++) {
parent.children[i].className = className;
}
}
</script>
<style>
#myMap {
position: relative;
width: 600px;
height: 400px;
}
.editButton, .selectedEditButton {
display:block;
float:left;
border:3px solid lightgray;
cursor:pointer;
background-color:lightgray;
margin:2px;
}
.colorBox, .selectedColorBox {
display:block;
float:left;
width:12px;
height:12px;
border:3px solid lightgray;
cursor:pointer;
margin:2px;
}
.selectedColorBox, .selectedEditButton {
border:3px solid blue;
}
</style>
</head>
<body>
<div id="myMap"></div>
<br />
<div id="DrawingModes">
<span class="editButton" onclick="setDrawingMode('pushpin', this)">Pushpin</span>
<span class="editButton" onclick="setDrawingMode('polyline', this)">Polyline</span>
<span class="editButton" onclick="setDrawingMode('polygon', this)">Polygon</span>
<span class="editButton" onclick="setDrawingMode('circle', this)">Circle</span>
<span class="editButton" onclick="setDrawingMode('rectangle', this)">Rectangle</span>
<span class="editButton" onclick="setDrawingMode('edit', this)">Edit</span>
<span class="editButton" onclick="setDrawingMode('erase', this)">Erase</span>
</div>
<br />
<br />
<!-- Simple Style Tools -->
<div style="height:25px">
<span style="float:left">Pushpin Icon Color:</span>
<div id="PushpinColors" style="float:left;">
<span class="colorBox" style="background-color:red" onclick="setPushpinColor(this)"></span>
<span class="colorBox" style="background-color:blue" onclick="setPushpinColor(this)"></span>
<span class="selectedColorBox" style="background-color:purple" onclick="setPushpinColor(this)"></span>
<span class="colorBox" style="background-color:green" onclick="setPushpinColor(this)"></span>
</div>
</div>
<div style="height:25px">
<span style="float:left">Fill Color:</span>
<div id="FillColors" style="float:left;">
<span class="colorBox" style="background-color:rgba(255,0,0,0.5)" onclick="setFillColor(this)"></span>
<span class="colorBox" style="background-color:rgba(0,0,255,0.5)" onclick="setFillColor(this)"></span>
<span class="colorBox" style="background-color:rgba(160,0,200,0.5)" onclick="setFillColor(this)"></span>
<span class="selectedColorBox" style="background-color:rgba(0,255,0,0.5)" onclick="setFillColor(this)"></span>
</div>
</div>
<div style="height:25px">
<span style="float:left">Stroke Color:</span>
<div id="StrokeColors" style="float:left;">
<span class="colorBox" style="background-color:red" onclick="setStrokeColor(this)"></span>
<span class="selectedColorBox" style="background-color:blue" onclick="setStrokeColor(this)"></span>
<span class="colorBox" style="background-color:purple" onclick="setStrokeColor(this)"></span>
<span class="colorBox" style="background-color:green" onclick="setStrokeColor(this)"></span>
</div>
</div>
Stroke Thickness:
<a href="javascript:setStrokeThickness(1);">1</a>
<a href="javascript:setStrokeThickness(3);">3</a>
<a href="javascript:setStrokeThickness(5);">5</a>
<a href="javascript:setStrokeThickness(7);">7</a>
<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>