Repository navigation
Expand file tree
/
Copy pathgoogle_map.js
More file actions
884 lines (740 loc) · 27.9 KB
/
Copy pathgoogle_map.js
File metadata and controls
884 lines (740 loc) · 27.9 KB
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
import React, {PropTypes, Component} from 'react';
import { isReact14 } from './utils/react_version';
import shouldPureComponentUpdate from 'react-pure-render/function';
import MarkerDispatcher from './marker_dispatcher';
import GoogleMapMap from './google_map_map';
import GoogleMapMarkers from './google_map_markers';
import GoogleMapMarkersPrerender from './google_map_markers_prerender';
import googleMapLoader from './utils/loaders/google_map_loader';
import detectBrowser from './utils/detect';
import Geo from './utils/geo';
import isArraysEqualEps from './utils/array_helper';
import isPlainObject from './utils/is_plain_object';
import pick from './utils/pick';
import raf from './utils/raf';
import log2 from './utils/math/log2';
import assign from 'lodash/object/assign';
import isNumber from 'lodash/lang/isNumber';
// To avoid Error with React 13, webpack will generate warning not error
// more details is here https://github.com/orgsync/react-list/pull/54
let ReactDOM;
if (isReact14(React)) {
try {
ReactDOM = require('react-dom');
} catch (e) {
ReactDOM = React;
}
} else {
ReactDOM = React;
}
const kEPS = 0.00001;
const K_GOOGLE_TILE_SIZE = 256;
// real minZoom calculated here _getMinZoom
const K_IDLE_TIMEOUT = 100;
const K_IDLE_CLICK_TIMEOUT = 300;
const DEFAULT_MIN_ZOOM = 3;
function defaultOptions_(/* maps */) {
return {
overviewMapControl: false,
streetViewControl: false,
rotateControl: true,
mapTypeControl: false,
// disable poi
styles: [{ featureType: 'poi', elementType: 'labels', stylers: [{ visibility: 'off' }]}],
minZoom: DEFAULT_MIN_ZOOM, // dynamically recalculted if possible during init
};
}
const style = {
width: '100%',
height: '100%',
margin: 0,
padding: 0,
position: 'relative',
};
const latLng2Obj = (latLng) => isPlainObject(latLng)
? latLng
: {lat: latLng[0], lng: latLng[1]};
export default class GoogleMap extends Component {
static propTypes = {
apiKey: PropTypes.string,
bootstrapURLKeys: PropTypes.any,
defaultCenter: React.PropTypes.oneOfType([
PropTypes.array,
PropTypes.shape({
lat: PropTypes.number,
lng: PropTypes.number,
}),
]),
center: React.PropTypes.oneOfType([
PropTypes.array,
PropTypes.shape({
lat: PropTypes.number,
lng: PropTypes.number,
}),
]),
defaultZoom: PropTypes.number,
zoom: PropTypes.number,
onBoundsChange: PropTypes.func,
onChange: PropTypes.func,
onClick: PropTypes.func,
onChildClick: PropTypes.func,
onChildMouseDown: PropTypes.func,
onChildMouseUp: PropTypes.func,
onChildMouseMove: PropTypes.func,
onChildMouseEnter: PropTypes.func,
onChildMouseLeave: PropTypes.func,
onZoomAnimationStart: PropTypes.func,
onZoomAnimationEnd: PropTypes.func,
onDrag: PropTypes.func,
options: PropTypes.any,
distanceToMouse: PropTypes.func,
hoverDistance: PropTypes.number,
debounced: PropTypes.bool,
margin: PropTypes.array,
googleMapLoader: PropTypes.any,
onGoogleApiLoaded: PropTypes.func,
yesIWantToUseGoogleMapApiInternals: PropTypes.bool,
draggable: PropTypes.bool,
};
static defaultProps = {
distanceToMouse(pt, mousePos /* , markerProps */) {
return Math.sqrt(
(pt.x - mousePos.x) * (pt.x - mousePos.x) + (pt.y - mousePos.y) * (pt.y - mousePos.y)
);
},
hoverDistance: 30,
debounced: true,
options: defaultOptions_,
googleMapLoader,
yesIWantToUseGoogleMapApiInternals: false,
};
static googleMapLoader = googleMapLoader; // eslint-disable-line
constructor(props) {
super(props);
this.mounted_ = false;
this.initialized_ = false;
this.googleApiLoadedCalled_ = false;
this.map_ = null;
this.maps_ = null;
this.prevBounds_ = null;
this.mouse_ = null;
this.mouseMoveTime_ = 0;
this.boundingRect_ = null;
this.mouseInMap_ = true;
this.dragTime_ = 0;
this.fireMouseEventOnIdle_ = false;
this.updateCounter_ = 0;
this.markersDispatcher_ = new MarkerDispatcher(this);
this.geoService_ = new Geo(K_GOOGLE_TILE_SIZE);
this.centerIsObject_ = isPlainObject(this.props.center);
this.minZoom_ = DEFAULT_MIN_ZOOM;
this.defaultDraggableOption_ = true;
this.zoomControlClickTime_ = 0;
this.childMouseDownArgs_ = null;
this.childMouseUpTime_ = 0;
if (process.env.NODE_ENV !== 'production') {
if (this.props.apiKey) {
console.warn( 'GoogleMap: ' + // eslint-disable-line no-console
'apiKey is deprecated, use ' +
'bootstrapURLKeys={{key: YOUR_API_KEY}} instead.');
}
if (this.props.onBoundsChange) {
console.warn( 'GoogleMap: ' + // eslint-disable-line no-console
'onBoundsChange is deprecated, use ' +
'onChange({center, zoom, bounds, ...other}) instead.');
}
if (this.props.center === undefined && this.props.defaultCenter === undefined) {
console.warn( 'GoogleMap: center or defaultCenter' + // eslint-disable-line no-console
'property must be defined');
}
if (this.props.zoom === undefined && this.props.defaultZoom === undefined) {
console.warn( 'GoogleMap: zoom or defaultZoom' + // eslint-disable-line no-console
'property must be defined');
}
}
if (this._isCenterDefined(this.props.center || this.props.defaultCenter)) {
const propsCenter = latLng2Obj(this.props.center || this.props.defaultCenter);
this.geoService_.setView(propsCenter, this.props.zoom || this.props.defaultZoom, 0);
}
this.zoomAnimationInProgress_ = false;
this.state = {
overlayCreated: false,
};
}
componentDidMount() {
this.mounted_ = true;
window.addEventListener('resize', this._onWindowResize);
window.addEventListener('keydown', this._onKeyDownCapture, true);
// gmap can't prevent map drag if mousedown event already occured
// the only workaround I find is prevent mousedown native browser event
ReactDOM.findDOMNode(this.refs.google_map_dom)
.addEventListener('mousedown', this._onMapMouseDownNative, true);
window.addEventListener('mouseup', this._onChildMouseUp, false);
const bootstrapURLKeys = {
...(this.props.apiKey && {key: this.props.apiKey}),
...this.props.bootstrapURLKeys,
};
this.props.googleMapLoader(bootstrapURLKeys); // we can start load immediatly
setTimeout(() => { // to detect size
this._setViewSize();
if (this._isCenterDefined(this.props.center || this.props.defaultCenter)) {
this._initMap();
}
}, 0, this);
}
componentWillReceiveProps(nextProps) {
if (process.env.NODE_ENV !== 'production') {
if (this.props.defaultCenter !== nextProps.defaultCenter) {
console.warn('GoogleMap: defaultCenter prop changed. ' + // eslint-disable-line
'You can\'t change default props.');
}
if (this.props.defaultZoom !== nextProps.defaultZoom) {
console.warn('GoogleMap: defaultZoom prop changed. ' + // eslint-disable-line
'You can\'t change default props.');
}
}
if (!this._isCenterDefined(this.props.center) && this._isCenterDefined(nextProps.center)) {
setTimeout(() =>
this._initMap(), 0);
}
if (this.map_) {
const centerLatLng = this.geoService_.getCenter();
if (nextProps.center) {
const nextPropsCenter = latLng2Obj(nextProps.center);
if (Math.abs(nextPropsCenter.lat - centerLatLng.lat) +
Math.abs(nextPropsCenter.lng - centerLatLng.lng) > kEPS) {
this.map_.panTo({lat: nextPropsCenter.lat, lng: nextPropsCenter.lng});
}
}
if (nextProps.zoom !== undefined) {
// if zoom chaged by user
if (Math.abs(nextProps.zoom - this.props.zoom) > 0) {
this.map_.setZoom(nextProps.zoom);
}
}
if (this.props.draggable !== undefined && nextProps.draggable === undefined) {
// reset to default
this.map_.setOptions({draggable: this.defaultDraggableOption_});
} else if (this.props.draggable !== nextProps.draggable) {
// also prevent this on window 'mousedown' event to prevent map move
this.map_.setOptions({draggable: nextProps.draggable});
}
}
}
shouldComponentUpdate = shouldPureComponentUpdate;
componentDidUpdate(prevProps) {
this.markersDispatcher_.emit('kON_CHANGE');
if (this.props.hoverDistance !== prevProps.hoverDistance) {
this.markersDispatcher_.emit('kON_MOUSE_POSITION_CHANGE');
}
}
componentWillUnmount() {
this.mounted_ = false;
window.removeEventListener('resize', this._onWindowResize);
window.removeEventListener('keydown', this._onKeyDownCapture);
ReactDOM.findDOMNode(this.refs.google_map_dom)
.removeEventListener('mousedown', this._onMapMouseDownNative, true);
window.removeEventListener('mouseup', this._onChildMouseUp, false);
if (this.overlay_) {
// this triggers overlay_.onRemove(), which will unmount the <GoogleMapMarkers/>
this.overlay_.setMap(null);
}
if (this.maps_ && this.map_) {
this.maps_.event.clearInstanceListeners(this.map_);
}
this.map_ = null;
this.maps_ = null;
this.markersDispatcher_.dispose();
this.resetSizeOnIdle_ = false;
delete this.map_;
delete this.markersDispatcher_;
}
// calc minZoom if map size available
// it's better to not set minZoom less than this calculation gives
// otherwise there is no homeomorphism between screen coordinates and map
// (one map coordinate can have different screen coordinates)
_getMinZoom = () => {
if (this.geoService_.getWidth() > 0 || this.geoService_.getHeight() > 0) {
const tilesPerWidth = Math.ceil(this.geoService_.getWidth() / K_GOOGLE_TILE_SIZE) + 2;
const tilesPerHeight = Math.ceil(this.geoService_.getHeight() / K_GOOGLE_TILE_SIZE) + 2;
const maxTilesPerDim = Math.max(tilesPerWidth, tilesPerHeight);
return Math.ceil(log2(maxTilesPerDim));
}
return DEFAULT_MIN_ZOOM;
}
_initMap = () => {
// only initialize the map once
if (this.initialized_) {
return;
}
this.initialized_ = true;
const propsCenter = latLng2Obj(this.props.center || this.props.defaultCenter);
this.geoService_.setView(propsCenter, this.props.zoom || this.props.defaultZoom, 0);
this._onBoundsChanged(); // now we can calculate map bounds center etc...
const bootstrapURLKeys = {
...(this.props.apiKey && {key: this.props.apiKey}),
...this.props.bootstrapURLKeys,
};
this.props.googleMapLoader(bootstrapURLKeys)
.then(maps => {
if (!this.mounted_) {
return;
}
const centerLatLng = this.geoService_.getCenter();
const propsOptions = {
zoom: this.props.zoom || this.props.defaultZoom,
center: new maps.LatLng(centerLatLng.lat, centerLatLng.lng),
};
// prevent to exapose full api
// next props must be exposed (console.log(Object.keys(pick(maps, isPlainObject))))
// "Animation", "ControlPosition", "MapTypeControlStyle", "MapTypeId",
// "NavigationControlStyle", "ScaleControlStyle", "StrokePosition",
// "SymbolPath", "ZoomControlStyle",
// "event", "DirectionsStatus", "DirectionsTravelMode", "DirectionsUnitSystem",
// "DistanceMatrixStatus",
// "DistanceMatrixElementStatus", "ElevationStatus", "GeocoderLocationType",
// "GeocoderStatus", "KmlLayerStatus",
// "MaxZoomStatus", "StreetViewStatus", "TransitMode", "TransitRoutePreference",
// "TravelMode", "UnitSystem"
const mapPlainObjects = pick(maps, isPlainObject);
const options = typeof this.props.options === 'function'
? this.props.options(mapPlainObjects)
: this.props.options;
const defaultOptions = defaultOptions_(mapPlainObjects);
const draggableOptions = this.props.draggable !== undefined &&
{draggable: this.props.draggable};
const minZoom = this._getMinZoom();
this.minZoom_ = minZoom;
const preMapOptions = {
...defaultOptions,
minZoom,
...options,
...propsOptions,
};
this.defaultDraggableOption_ = preMapOptions.draggable !== undefined
? preMapOptions.draggable
: this.defaultDraggableOption_;
const mapOptions = {
...preMapOptions,
...draggableOptions,
};
if (process.env.NODE_ENV !== 'production') {
if (mapOptions.minZoom < minZoom) {
console.warn( 'GoogleMap: ' + // eslint-disable-line
'minZoom option is less than recommended ' +
'minZoom option for your map sizes.\n' +
'overrided to value ' + minZoom);
}
}
if (mapOptions.minZoom < minZoom) {
mapOptions.minZoom = minZoom;
}
const map = new maps.Map(ReactDOM.findDOMNode(this.refs.google_map_dom), mapOptions);
this.map_ = map;
this.maps_ = maps;
// render in overlay
const this_ = this;
const overlay = this.overlay_ = assign(new maps.OverlayView(), {
onAdd() {
const K_MAX_WIDTH = (typeof screen !== 'undefined') ? `${screen.width}px` : '2000px';
const K_MAX_HEIGHT = (typeof screen !== 'undefined') ? `${screen.height}px` : '2000px';
const div = document.createElement('div');
this.div = div;
div.style.backgroundColor = 'transparent';
div.style.position = 'absolute';
div.style.left = '0px';
div.style.top = '0px';
div.style.width = K_MAX_WIDTH; // prevents some chrome draw defects
div.style.height = K_MAX_HEIGHT;
const panes = this.getPanes();
panes.overlayMouseTarget.appendChild(div);
ReactDOM.render((
<GoogleMapMarkers
onChildClick={this_._onChildClick}
onChildMouseDown={this_._onChildMouseDown}
onChildMouseEnter={this_._onChildMouseEnter}
onChildMouseLeave={this_._onChildMouseLeave}
geoService={this_.geoService_}
projectFromLeftTop
distanceToMouse={this_.props.distanceToMouse}
getHoverDistance={this_._getHoverDistance}
dispatcher={this_.markersDispatcher_} />),
div,
// remove prerendered markers
() => this_.setState({overlayCreated: true}),
);
},
onRemove() {
ReactDOM.unmountComponentAtNode(this.div);
},
draw() {
const div = overlay.div;
const overlayProjection = overlay.getProjection();
const bounds = map.getBounds();
const ne = bounds.getNorthEast();
const sw = bounds.getSouthWest();
const ptx = overlayProjection.fromLatLngToDivPixel(new maps.LatLng(ne.lat(), sw.lng()));
// need round for safari still can't find what need for firefox
const ptxRounded = detectBrowser().isSafari
? {x: Math.round(ptx.x), y: Math.round(ptx.y)}
: {x: ptx.x, y: ptx.y};
this_.updateCounter_++;
this_._onBoundsChanged(map, maps, !this_.props.debounced);
if (!this_.googleApiLoadedCalled_) {
this_._onGoogleApiLoaded({map, maps});
this_.googleApiLoadedCalled_ = true;
}
div.style.left = `${ptxRounded.x}px`;
div.style.top = `${ptxRounded.y}px`;
if (this_.markersDispatcher_) {
this_.markersDispatcher_.emit('kON_CHANGE');
}
},
});
overlay.setMap(map);
maps.event.addListener(map, 'zoom_changed', () => {
// recalc position at zoom start
if (this_.geoService_.getZoom() !== map.getZoom()) {
if (!this_.zoomAnimationInProgress_) {
this_.zoomAnimationInProgress_ = true;
this_._onZoomAnimationStart();
}
const TIMEOUT_ZOOM = 300;
if ((new Date()).getTime() - this.zoomControlClickTime_ < TIMEOUT_ZOOM) {
// there is strange Google Map Api behavior in chrome when zoom animation of map
// is started only on second raf call, if was click on zoom control
// or +- keys pressed, so i wait for two rafs before change state
// this does not fully prevent animation jump
// but reduce it's occurence probability
raf(() => raf(() => {
this_.updateCounter_++;
this_._onBoundsChanged(map, maps);
}));
} else {
this_.updateCounter_++;
this_._onBoundsChanged(map, maps);
}
}
});
maps.event.addListener(map, 'idle', () => {
if (this.resetSizeOnIdle_) {
this._setViewSize();
const currMinZoom = this._getMinZoom();
if (currMinZoom !== this.minZoom_) {
this.minZoom_ = currMinZoom;
map.setOptions({minZoom: currMinZoom});
}
this.resetSizeOnIdle_ = false;
}
if (this_.zoomAnimationInProgress_) {
this_.zoomAnimationInProgress_ = false;
this_._onZoomAnimationEnd();
}
const div = overlay.div;
const overlayProjection = overlay.getProjection();
const bounds = map.getBounds();
const ne = bounds.getNorthEast();
const sw = bounds.getSouthWest();
const ptx = overlayProjection.fromLatLngToDivPixel(new maps.LatLng(ne.lat(), sw.lng()));
// need round for safari still can't find what need for firefox
const ptxRounded = detectBrowser().isSafari
? {x: Math.round(ptx.x), y: Math.round(ptx.y)}
: {x: ptx.x, y: ptx.y};
this_.updateCounter_++;
this_._onBoundsChanged(map, maps);
if (this.mouse_) {
const latLng = this.geoService_.unproject(this.mouse_, true);
this.mouse_.lat = latLng.lat;
this.mouse_.lng = latLng.lng;
}
this._onChildMouseMove();
this_.dragTime_ = 0;
div.style.left = `${ptxRounded.x}px`;
div.style.top = `${ptxRounded.y}px`;
if (this_.markersDispatcher_) {
this_.markersDispatcher_.emit('kON_CHANGE');
if (this_.fireMouseEventOnIdle_) {
this_.markersDispatcher_.emit('kON_MOUSE_POSITION_CHANGE');
}
}
});
maps.event.addListener(map, 'mouseover', () => { // has advantage over div MouseLeave
this_.mouseInMap_ = true;
});
maps.event.addListener(map, 'mouseout', () => { // has advantage over div MouseLeave
this_.mouseInMap_ = false;
this_.mouse_ = null;
this_.markersDispatcher_.emit('kON_MOUSE_POSITION_CHANGE');
});
maps.event.addListener(map, 'drag', () => {
this_.dragTime_ = (new Date()).getTime();
this_._onDrag();
});
})
.catch( e => {
console.error(e); // eslint-disable-line no-console
throw e;
});
}
_onGoogleApiLoaded = (...args) => {
if (this.props.onGoogleApiLoaded) {
if (process.env.NODE_ENV !== 'production' &&
this.props.yesIWantToUseGoogleMapApiInternals !== true ) {
console.warn( 'GoogleMap: ' + // eslint-disable-line
'Usage of internal api objects is dangerous ' +
'and can cause a lot of issues.\n' +
'To hide this warning add yesIWantToUseGoogleMapApiInternals={true} ' +
'to <GoogleMap instance');
}
this.props.onGoogleApiLoaded(...args);
}
}
_getHoverDistance = () => {
return this.props.hoverDistance;
}
_onDrag = (...args) => this.props.onDrag &&
this.props.onDrag(...args);
_onZoomAnimationStart = (...args) => this.props.onZoomAnimationStart &&
this.props.onZoomAnimationStart(...args)
_onZoomAnimationEnd = (...args) => this.props.onZoomAnimationEnd &&
this.props.onZoomAnimationEnd(...args)
_onChildClick = (...args) => {
if (this.props.onChildClick) {
return this.props.onChildClick(...args);
}
}
_onChildMouseDown = (hoverKey, childProps) => {
if (this.props.onChildMouseDown) {
this.childMouseDownArgs_ = [hoverKey, childProps];
this.props.onChildMouseDown(hoverKey, childProps, {...this.mouse_});
}
}
// this method works only if this.props.onChildMouseDown was called
_onChildMouseUp = () => {
if (this.childMouseDownArgs_) {
if (this.props.onChildMouseUp) {
this.props.onChildMouseUp(...this.childMouseDownArgs_, {...this.mouse_});
}
this.childMouseDownArgs_ = null;
this.childMouseUpTime_ = (new Date()).getTime();
}
}
// this method works only if this.props.onChildMouseDown was called
_onChildMouseMove = () => {
if (this.childMouseDownArgs_) {
if (this.props.onChildMouseMove) {
this.props.onChildMouseMove(...this.childMouseDownArgs_, {...this.mouse_});
}
}
}
_onChildMouseEnter = (...args) => {
if (this.props.onChildMouseEnter) {
return this.props.onChildMouseEnter(...args);
}
}
_onChildMouseLeave = (...args) => {
if (this.props.onChildMouseLeave) {
return this.props.onChildMouseLeave(...args);
}
}
_setViewSize = () => {
const mapDom = ReactDOM.findDOMNode(this.refs.google_map_dom);
this.geoService_.setViewSize(mapDom.clientWidth, mapDom.clientHeight);
this._onBoundsChanged();
}
_onWindowResize = () => {
this.resetSizeOnIdle_ = true;
}
_onMapMouseMove = (e) => {
if (!this.mouseInMap_) return;
const currTime = (new Date()).getTime();
const K_RECALC_CLIENT_RECT_MS = 50;
if (currTime - this.mouseMoveTime_ > K_RECALC_CLIENT_RECT_MS) {
this.boundingRect_ = e.currentTarget.getBoundingClientRect();
}
this.mouseMoveTime_ = currTime;
const mousePosX = e.clientX - this.boundingRect_.left;
const mousePosY = e.clientY - this.boundingRect_.top;
if (!this.mouse_) {
this.mouse_ = {x: 0, y: 0, lat: 0, lng: 0};
}
this.mouse_.x = mousePosX;
this.mouse_.y = mousePosY;
const latLng = this.geoService_.unproject(this.mouse_, true);
this.mouse_.lat = latLng.lat;
this.mouse_.lng = latLng.lng;
this._onChildMouseMove();
if (currTime - this.dragTime_ < K_IDLE_TIMEOUT) {
this.fireMouseEventOnIdle_ = true;
} else {
this.markersDispatcher_.emit('kON_MOUSE_POSITION_CHANGE');
this.fireMouseEventOnIdle_ = false;
}
}
// K_IDLE_CLICK_TIMEOUT - looks like 300 is enough
_onClick = (...args) =>
this.props.onClick &&
!this.childMouseDownArgs_ &&
((new Date()).getTime() - this.childMouseUpTime_) > K_IDLE_CLICK_TIMEOUT &&
this.dragTime_ === 0 &&
this.props.onClick(...args)
_onMapClick = (event) => {
if (this.markersDispatcher_) {
const currTime = (new Date()).getTime();
if (currTime - this.dragTime_ > K_IDLE_TIMEOUT) {
if (this.mouse_) {
this._onClick({
...this.mouse_,
event,
});
}
this.markersDispatcher_.emit('kON_CLICK', event);
}
}
}
// gmap can't prevent map drag if mousedown event already occured
// the only workaround I find is prevent mousedown native browser event
_onMapMouseDownNative = (event) => {
if (!this.mouseInMap_) return;
this._onMapMouseDown(event);
if (this.props.draggable === false) {
event.preventDefault();
event.stopPropagation();
}
}
_onMapMouseDown = (event) => {
if (this.markersDispatcher_) {
const currTime = (new Date()).getTime();
if (currTime - this.dragTime_ > K_IDLE_TIMEOUT) {
this.markersDispatcher_.emit('kON_MDOWN', event);
}
}
}
_onMapMouseDownCapture = () => {
if (detectBrowser().isChrome) {
// to fix strange zoom in chrome
if (!this.mouse_) {
this.zoomControlClickTime_ = (new Date()).getTime();
}
}
}
_onKeyDownCapture = () => {
if (detectBrowser().isChrome) {
this.zoomControlClickTime_ = (new Date()).getTime();
}
}
_isCenterDefined = (center) => center && (
(isPlainObject(center) && isNumber(center.lat) && isNumber(center.lng)) ||
(center.length === 2 && isNumber(center[0]) && isNumber(center[1]))
)
_onBoundsChanged = (map, maps, callExtBoundsChange) => {
if (map) {
const gmC = map.getCenter();
this.geoService_.setView([gmC.lat(), gmC.lng()], map.getZoom(), 0);
}
if ((this.props.onChange || this.props.onBoundsChange) && this.geoService_.canProject()) {
const zoom = this.geoService_.getZoom();
const bounds = this.geoService_.getBounds();
const centerLatLng = this.geoService_.getCenter();
if (!isArraysEqualEps(bounds, this.prevBounds_, kEPS)) {
if (callExtBoundsChange !== false) {
const marginBounds = this.geoService_.getBounds(this.props.margin);
if (this.props.onBoundsChange) {
this.props.onBoundsChange(
this.centerIsObject_
? {...centerLatLng}
: [centerLatLng.lat, centerLatLng.lng],
zoom,
bounds,
marginBounds
);
}
if (this.props.onChange) {
this.props.onChange({
center: {...centerLatLng},
zoom,
bounds: {
nw: {
lat: bounds[0],
lng: bounds[1],
},
se: {
lat: bounds[2],
lng: bounds[3],
},
},
marginBounds: {
nw: {
lat: marginBounds[0],
lng: marginBounds[1],
},
se: {
lat: marginBounds[2],
lng: marginBounds[3],
},
},
size: this.geoService_.hasSize()
? {
width: this.geoService_.getWidth(),
height: this.geoService_.getHeight(),
}
: {
width: 0,
height: 0,
},
});
}
this.prevBounds_ = bounds;
}
}
// uncomment for strange bugs
if (process.env.NODE_ENV !== 'production') { // compare with google calculations
if (map) {
const locBounds = map.getBounds();
const ne = locBounds.getNorthEast();
const sw = locBounds.getSouthWest();
const gmC = map.getCenter();
// compare with google map
if (!isArraysEqualEps(
[centerLatLng.lat, centerLatLng.lng],
[gmC.lat(), gmC.lng()], kEPS
)) {
console.info('GoogleMap center not eq:', // eslint-disable-line no-console
[centerLatLng.lat, centerLatLng.lng], [gmC.lat(), gmC.lng()]);
}
if (!isArraysEqualEps(bounds, [ne.lat(), sw.lng(), sw.lat(), ne.lng()], kEPS)) {
// this is normal if this message occured on resize
console.info('GoogleMap bounds not eq:', '\n', // eslint-disable-line no-console
bounds, '\n', [ne.lat(), sw.lng(), sw.lat(), ne.lng()]);
}
}
}
}
}
render() {
const mapMarkerPrerender = !this.state.overlayCreated ? (
<GoogleMapMarkersPrerender
onChildClick={this._onChildClick}
onChildMouseDown={this._onChildMouseDown}
onChildMouseEnter={this._onChildMouseEnter}
onChildMouseLeave={this._onChildMouseLeave}
geoService={this.geoService_}
projectFromLeftTop={false}
distanceToMouse={this.props.distanceToMouse}
getHoverDistance={this._getHoverDistance}
dispatcher={this.markersDispatcher_} />
) : null;
return (
<div
style={style}
onMouseMove={this._onMapMouseMove}
onMouseDownCapture={this._onMapMouseDownCapture}
onClick={this._onMapClick}
>
<GoogleMapMap ref="google_map_dom" />
{/* render markers before map load done */}
{mapMarkerPrerender}
</div>
);
}
}