forked from emedvedev/google-map
-
Notifications
You must be signed in to change notification settings - Fork 2
/
google-map.js
832 lines (715 loc) · 21.4 KB
/
google-map.js
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
import { Polymer } from '../../@polymer/polymer/lib/legacy/polymer-fn.js';
import { html } from '../../@polymer/polymer/lib/utils/html-tag.js';
import { IronResizableBehavior } from '../../@polymer/iron-resizable-behavior/iron-resizable-behavior.js';
import './google-map-marker.js';
import '../../@johnriv/google-apis/google-maps-api.js';
/* Copyright (c) 2015 Google Inc. All rights reserved. */
/**
The `google-map` element renders a Google Map.
<b>Example</b>:
<style>
google-map {
height: 600px;
}
</style>
<google-map latitude="37.77493" longitude="-122.41942" api-key="1234"></google-map>
<b>Example</b> - add markers to the map and ensure they're in view:
<google-map latitude="37.77493" longitude="-122.41942" fit-to-markers>
<google-map-marker latitude="37.779" longitude="-122.3892"
draggable="true" title="Go Giants!"></google-map-marker>
<google-map-marker latitude="37.777" longitude="-122.38911"></google-map-marker>
</google-map>
<b>Example</b>:
<google-map disable-default-ui zoom="15"></google-map>
<script>
var map = document.querySelector('google-map');
map.latitude = 37.77493;
map.longitude = -122.41942;
map.addEventListener('google-map-ready', function(e) {
alert('Map loaded!');
});
</script>
<b>Example</b> - with Google directions, using data-binding inside another Polymer element
<google-map map="{{map}}"></google-map>
<google-map-directions map="[[map]]"
start-address="San Francisco" end-address="Mountain View">
</google-map-directions>
Disable dragging by adding `draggable="false"` on the `google-map` element.
<b>Example</b> - loading the Maps API from another origin (China)
<google-map maps-url="http://maps.google.cn/maps/api/js?callback=%%callback%%">
### Tips
If you're seeing the message "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." it probably means you're loading other maps elements on the page (`<google-maps-directions>`). Each maps element must include the same set of configuration options (`apiKey`, `clientId`, `language`, `version`, etc.) so the Maps API is loaded from the same URL.
@demo demo/index.html
@demo demo/polys.html
@demo demo/kml.html
*/
Polymer({
_template: html`
<style>
:host {
position: relative;
display: block;
height: 100%;
}
#map {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
<google-maps-api id="api" api-key="[[apiKey]]" client-id="[[clientId]]" version="[[version]]" signed-in="[[signedIn]]" language="[[language]]" on-api-load="_mapApiLoaded" maps-url="[[mapsUrl]]">
</google-maps-api>
<div id="map"></div>
<iron-selector id="selector" multi="[[!singleInfoWindow]]" selected-attribute="open" activate-event="google-map-marker-open" on-google-map-marker-close="_deselectMarker">
<slot id="markers" name="markers"></slot>
</iron-selector>
<slot id="objects"></slot>
`,
is: 'google-map',
/**
* Fired when the Maps API has fully loaded.
*
* @event google-map-ready
*/
/**
* Fired when the user clicks on the map (but not when they click on a marker, infowindow, or
* other object). Requires the clickEvents attribute to be true.
*
* @event google-map-click
* @param {google.maps.MouseEvent} event The mouse event.
*/
/**
* Fired when the user double-clicks on the map. Note that the google-map-click event will also fire,
* right before this one. Requires the clickEvents attribute to be true.
*
* @event google-map-dblclick
* @param {google.maps.MouseEvent} event The mouse event.
*/
/**
* Fired repeatedly while the user drags the map. Requires the dragEvents attribute to be true.
*
* @event google-map-drag
*/
/**
* Fired when the user stops dragging the map. Requires the dragEvents attribute to be true.
*
* @event google-map-dragend
*/
/**
* Fired when the user starts dragging the map. Requires the dragEvents attribute to be true.
*
* @event google-map-dragstart
*/
/**
* Fired whenever the user's mouse moves over the map container. Requires the mouseEvents attribute to
* be true.
*
* @event google-map-mousemove
* @param {google.maps.MouseEvent} event The mouse event.
*/
/**
* Fired when the user's mouse exits the map container. Requires the mouseEvents attribute to be true.
*
* @event google-map-mouseout
* @param {google.maps.MouseEvent} event The mouse event.
*/
/**
* Fired when the user's mouse enters the map container. Requires the mouseEvents attribute to be true.
*
* @event google-map-mouseover
* @param {google.maps.MouseEvent} event The mouse event.
*/
/**
* Fired when the DOM `contextmenu` event is fired on the map container. Requires the clickEvents
* attribute to be true.
*
* @event google-map-rightclick
* @param {google.maps.MouseEvent} event The mouse event.
*/
/**
* Fired when the map becomes idle after panning or zooming.
*
* @event google-map-idle
*/
/**
* Polymer properties for the google-map custom element.
*/
properties: {
/**
* A Maps API key. To obtain an API key, see https://developers.google.com/maps/documentation/javascript/tutorial#api_key.
*/
apiKey: String,
/**
* Overrides the origin the Maps API is loaded from. Defaults to `https://maps.googleapis.com`.
*/
mapsUrl: {
type: String,
// Initial value set in google-maps-api.
},
/**
* A Maps API for Business Client ID. To obtain a Maps API for Business Client ID, see https://developers.google.com/maps/documentation/business/.
* If set, a Client ID will take precedence over an API Key.
*/
clientId: String,
/**
* A latitude to center the map on.
*/
latitude: {
type: Number,
value: 37.77493,
notify: true,
reflectToAttribute: true,
},
/**
* A Maps API object.
*/
map: {
type: Object,
notify: true,
value: null,
},
/**
* A longitude to center the map on.
*/
longitude: {
type: Number,
value: -122.41942,
notify: true,
reflectToAttribute: true,
},
/**
* A kml file to load.
*/
kml: {
type: String,
value: null,
observer: '_loadKml',
},
/**
* A zoom level to set the map to.
*/
zoom: {
type: Number,
value: 10,
observer: '_zoomChanged',
notify: true,
},
/**
* When set, prevents the map from tilting (when the zoom level and viewport supports it).
*/
noAutoTilt: {
type: Boolean,
value: false,
},
/**
* Map type to display. One of 'roadmap', 'satellite', 'hybrid', 'terrain'.
*/
mapType: {
type: String,
value: 'roadmap', // roadmap, satellite, hybrid, terrain,
observer: '_mapTypeChanged',
notify: true,
},
/**
* Version of the Google Maps API to use.
*/
version: {
type: String,
value: '3.exp',
},
/**
* If set, removes the map's default UI controls.
*/
disableDefaultUi: {
type: Boolean,
value: false,
observer: '_disableDefaultUiChanged',
},
/**
* If set, removes the map's 'map type' UI controls.
*/
disableMapTypeControl: {
type: Boolean,
value: false,
observer: '_disableMapTypeControlChanged',
},
/**
* If set, removes the map's 'street view' UI controls.
*/
disableStreetViewControl: {
type: Boolean,
value: false,
observer: '_disableStreetViewControlChanged',
},
/**
* If set, the zoom level is set such that all markers (google-map-marker children) are brought into view.
*/
fitToMarkers: {
type: Boolean,
value: false,
observer: '_fitToMarkersChanged',
},
/**
* If true, prevent the user from zooming the map interactively.
*/
disableZoom: {
type: Boolean,
value: false,
observer: '_disableZoomChanged',
},
/**
* If set, custom styles can be applied to the map.
* For style documentation see https://developers.google.com/maps/documentation/javascript/reference#MapTypeStyle
*/
styles: {
type: Object,
value() { return {}; },
},
/**
* A maximum zoom level which will be displayed on the map.
*/
maxZoom: {
type: Number,
observer: '_maxZoomChanged',
},
/**
* A minimum zoom level which will be displayed on the map.
*/
minZoom: {
type: Number,
observer: '_minZoomChanged',
},
/**
* If true, sign-in is enabled.
* See https://developers.google.com/maps/documentation/javascript/signedin#enable_sign_in
*/
signedIn: {
type: Boolean,
value: false,
},
/**
* The localized language to load the Maps API with. For more information
* see https://developers.google.com/maps/documentation/javascript/basics#Language
*
* Note: the Maps API defaults to the preffered language setting of the browser.
* Use this parameter to override that behavior.
*/
language: {
type: String,
},
/**
* When true, map *click events are automatically registered.
*/
clickEvents: {
type: Boolean,
value: false,
observer: '_clickEventsChanged',
},
/**
* When true, map drag* events are automatically registered.
*/
dragEvents: {
type: Boolean,
value: false,
observer: '_dragEventsChanged',
},
/**
* When true, map mouse* events are automatically registered.
*/
mouseEvents: {
type: Boolean,
value: false,
observer: '_mouseEventsChanged',
},
/**
* Additional map options for google.maps.Map constructor.
* Use to specify additional options we do not expose as
* properties.
* Ex: `<google-map additional-map-options='{"mapTypeId":"satellite"}'>`
*
* Note, you can't use API enums like `google.maps.ControlPosition.TOP_RIGHT`
* when using this property as an HTML attribute. Instead, use the actual
* value (e.g. `3`) or set `.additionalMapOptions` in JS rather than using
* the attribute.
*/
additionalMapOptions: {
type: Object,
value() { return {}; },
},
/**
* The markers on the map.
*/
markers: {
type: Array,
value() { return []; },
readOnly: true,
},
/**
* The non-marker objects on the map.
*/
objects: {
type: Array,
value() { return []; },
readOnly: true,
},
/**
* If set, all other info windows on markers are closed when opening a new one.
*/
singleInfoWindow: {
type: Boolean,
value: false,
},
},
listeners: {
'iron-resize': 'resize',
},
observers: [
'_debounceUpdateCenter(latitude, longitude)',
],
attached() {
this._initGMap();
},
detached() {
if (this._markersChildrenListener) {
this.unlisten(this.$.selector, 'items-changed', '_updateMarkers');
this._markersChildrenListener = null;
}
if (this._objectsMutationObserver) {
this._objectsMutationObserver.disconnect();
this._objectsMutationObserver = null;
}
},
behaviors: [
IronResizableBehavior,
],
_initGMap() {
if (this.map) {
return; // already initialized
}
if (this.$.api.libraryLoaded !== true) {
return; // api not loaded
}
if (!this.isAttached) {
return; // not attached
}
this.map = new google.maps.Map(this.$.map, this._getMapOptions());
this._listeners = {};
this._updateCenter();
this._loadKml();
this._updateMarkers();
this._updateObjects();
this._addMapListeners();
this.fire('google-map-ready');
},
_mapApiLoaded() {
this._initGMap();
},
_getMapOptions() {
const mapOptions = {
zoom: this.zoom,
tilt: this.noAutoTilt ? 0 : 45,
mapTypeId: this.mapType,
disableDefaultUI: this.disableDefaultUi,
mapTypeControl: !this.disableDefaultUi && !this.disableMapTypeControl,
streetViewControl: !this.disableDefaultUi && !this.disableStreetViewControl,
disableDoubleClickZoom: this.disableZoom,
scrollwheel: !this.disableZoom,
styles: this.styles,
maxZoom: Number(this.maxZoom),
minZoom: Number(this.minZoom),
};
// Only override the default if set.
// We use getAttribute here because the default value of this.draggable = false even when not set.
if (this.getAttribute('draggable') != null) {
mapOptions.draggable = this.draggable;
}
for (const p in this.additionalMapOptions) { mapOptions[p] = this.additionalMapOptions[p]; }
return mapOptions;
},
_attachChildrenToMap(children) {
if (this.map) {
for (var i = 0, child; child = children[i]; ++i) {
child.map = this.map;
}
}
},
// watch for future updates to marker objects
_observeMarkers() {
// Watch for future updates.
if (this._markersChildrenListener) {
return;
}
this._markersChildrenListener = this.listen(this.$.selector, 'items-changed', '_updateMarkers');
},
_updateMarkers() {
const newMarkers = Array.prototype.slice.call(this.$.markers.assignedNodes({ flatten: true }));
// do not recompute if markers have not been added or removed
if (newMarkers.length === this.markers.length) {
const added = newMarkers.filter(m => this.markers && this.markers.indexOf(m) === -1);
if (added.length === 0) {
// set up observer first time around
if (!this._markersChildrenListener) {
this._observeMarkers();
}
return;
}
}
this._observeMarkers();
this.markers = this._setMarkers(newMarkers);
// Set the map on each marker and zoom viewport to ensure they're in view.
this._attachChildrenToMap(this.markers);
if (this.fitToMarkers) {
this._fitToMarkersChanged();
}
},
// watch for future updates to non-marker objects
_observeObjects() {
if (this._objectsMutationObserver) {
return;
}
this._objectsMutationObserver = new MutationObserver(this._updateObjects.bind(this));
this._objectsMutationObserver.observe(this, {
childList: true,
});
},
_updateObjects() {
const newObjects = Array.prototype.slice.call(this.$.objects.assignedNodes({ flatten: true }));
// Do not recompute if objects have not been added or removed.
if (newObjects.length === this.objects.length) {
const added = newObjects.filter(o => this.objects.indexOf(o) === -1);
if (added.length === 0) {
// Set up observer first time around.
this._observeObjects();
return;
}
}
this._observeObjects();
this._setObjects(newObjects);
this._attachChildrenToMap(this.objects);
},
/**
* Clears all markers from the map.
*
* @method clear
*/
clear() {
for (var i = 0, m; m = this.markers[i]; ++i) {
m.marker.setMap(null);
}
},
/**
* Explicitly resizes the map, updating its center. This is useful if the
* map does not show after you have unhidden it.
*
* @method resize
*/
resize() {
if (this.map) {
// saves and restores latitude/longitude because resize can move the center
const oldLatitude = this.latitude;
const oldLongitude = this.longitude;
google.maps.event.trigger(this.map, 'resize');
this.latitude = oldLatitude; // restore because resize can move our center
this.longitude = oldLongitude;
if (this.fitToMarkers) { // we might not have a center if we are doing fit-to-markers
this._fitToMarkersChanged();
}
}
},
_loadKml() {
if (this.map && this.kml) {
const kmlfile = new google.maps.KmlLayer({
url: this.kml,
map: this.map,
});
}
},
_debounceUpdateCenter() {
this.debounce('updateCenter', this._updateCenter);
},
_updateCenter() {
this.cancelDebouncer('updateCenter');
if (this.map && this.latitude !== undefined && this.longitude !== undefined) {
// allow for latitude and longitude to be String-typed, but still Number valued
const lati = Number(this.latitude);
if (isNaN(lati)) {
throw new TypeError('latitude must be a number');
}
const longi = Number(this.longitude);
if (isNaN(longi)) {
throw new TypeError('longitude must be a number');
}
const newCenter = new google.maps.LatLng(lati, longi);
let oldCenter = this.map.getCenter();
if (!oldCenter) {
// If the map does not have a center, set it right away.
this.map.setCenter(newCenter);
} else {
// Using google.maps.LatLng returns corrected lat/lngs.
oldCenter = new google.maps.LatLng(oldCenter.lat(), oldCenter.lng());
// If the map currently has a center, slowly pan to the new one.
if (!oldCenter.equals(newCenter)) {
this.map.panTo(newCenter);
}
}
}
},
_zoomChanged() {
if (this.map) {
this.map.setZoom(Number(this.zoom));
}
},
_idleEvent() {
if (this.map) {
this._forwardEvent('idle');
} else {
this._clearListener('idle');
}
},
_clickEventsChanged() {
if (this.map) {
if (this.clickEvents) {
this._forwardEvent('click');
this._forwardEvent('dblclick');
this._forwardEvent('rightclick');
} else {
this._clearListener('click');
this._clearListener('dblclick');
this._clearListener('rightclick');
}
}
},
_dragEventsChanged() {
if (this.map) {
if (this.dragEvents) {
this._forwardEvent('drag');
this._forwardEvent('dragend');
this._forwardEvent('dragstart');
} else {
this._clearListener('drag');
this._clearListener('dragend');
this._clearListener('dragstart');
}
}
},
_mouseEventsChanged() {
if (this.map) {
if (this.mouseEvents) {
this._forwardEvent('mousemove');
this._forwardEvent('mouseout');
this._forwardEvent('mouseover');
} else {
this._clearListener('mousemove');
this._clearListener('mouseout');
this._clearListener('mouseover');
}
}
},
_maxZoomChanged() {
if (this.map) {
this.map.setOptions({ maxZoom: Number(this.maxZoom) });
}
},
_minZoomChanged() {
if (this.map) {
this.map.setOptions({ minZoom: Number(this.minZoom) });
}
},
_mapTypeChanged() {
if (this.map) {
this.map.setMapTypeId(this.mapType);
}
},
_disableDefaultUiChanged() {
if (!this.map) {
return;
}
this.map.setOptions({ disableDefaultUI: this.disableDefaultUi });
},
_disableMapTypeControlChanged() {
if (!this.map) {
return;
}
this.map.setOptions({ mapTypeControl: !this.disableMapTypeControl });
},
_disableStreetViewControlChanged() {
if (!this.map) {
return;
}
this.map.setOptions({ streetViewControl: !this.disableStreetViewControl });
},
_disableZoomChanged() {
if (!this.map) {
return;
}
this.map.setOptions({
disableDoubleClickZoom: this.disableZoom,
scrollwheel: !this.disableZoom,
});
},
attributeChanged(attrName) {
if (!this.map) {
return;
}
// Cannot use *Changed watchers for native properties.
switch (attrName) {
case 'draggable':
this.map.setOptions({ draggable: this.draggable });
break;
}
},
_fitToMarkersChanged() {
// TODO(ericbidelman): respect user's zoom level.
if (this.map && this.fitToMarkers && this.markers.length > 0) {
const latLngBounds = new google.maps.LatLngBounds();
for (var i = 0, m; m = this.markers[i]; ++i) {
latLngBounds.extend(new google.maps.LatLng(m.latitude, m.longitude));
}
// For one marker, don't alter zoom, just center it.
if (this.markers.length > 1) {
this.map.fitBounds(latLngBounds);
}
this.map.setCenter(latLngBounds.getCenter());
}
},
_addMapListeners() {
google.maps.event.addListener(this.map, 'center_changed', () => {
const center = this.map.getCenter();
this.latitude = center.lat();
this.longitude = center.lng();
});
google.maps.event.addListener(this.map, 'zoom_changed', () => {
this.zoom = this.map.getZoom();
});
google.maps.event.addListener(this.map, 'maptypeid_changed', () => {
this.mapType = this.map.getMapTypeId();
});
this._clickEventsChanged();
this._dragEventsChanged();
this._mouseEventsChanged();
this._idleEvent();
},
_clearListener(name) {
if (this._listeners[name]) {
google.maps.event.removeListener(this._listeners[name]);
this._listeners[name] = null;
}
},
_forwardEvent(name) {
this._listeners[name] = google.maps.event.addListener(this.map, name, (event) => {
this.fire(`google-map-${name}`, event);
});
},
_deselectMarker(e, detail) {
// If singleInfoWindow is set, update iron-selector's selected attribute to be null.
// Else remove the marker from iron-selector's selected array.
const markerIndex = this.$.selector.indexOf(e.target);
if (this.singleInfoWindow) {
this.$.selector.selected = null;
} else if (this.$.selector.selectedValues) {
this.$.selector.selectedValues = this.$.selector.selectedValues.filter(i => i !== markerIndex);
}
},
});