aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/MapBox/MapBox.tsx
blob: bfb0a6161bbd2d54fb5baa03f427d7bf34877746 (plain)
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { GoogleMapProps, Marker } from '@react-google-maps/api';
import BingMapsReact from 'bingmaps-react';
import { EditableText } from 'browndash-components';
import e from 'connect-flash';
import { truncateSync } from 'fs';
import { action, computed, IReactionDisposer, observable, ObservableMap, reaction, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { Doc, DocListCast, Opt } from '../../../../fields/Doc';
import { Width } from '../../../../fields/DocSymbols';
import { Id } from '../../../../fields/FieldSymbols';
import { InkTool } from '../../../../fields/InkField';
import { ScriptField } from '../../../../fields/ScriptField';
import { NumCast, StrCast } from '../../../../fields/Types';
import { emptyFunction, returnAll, returnEmptyDoclist, returnEmptyString, returnFalse, returnIgnore, returnOne, setupMoveUpEvents, Utils } from '../../../../Utils';
import { Docs } from '../../../documents/Documents';
import { DragManager } from '../../../util/DragManager';
import { SnappingManager } from '../../../util/SnappingManager';
import { Transform } from '../../../util/Transform';
import { UndoManager } from '../../../util/UndoManager';
import { MarqueeOptionsMenu } from '../../collections/collectionFreeForm';
import { ViewBoxAnnotatableComponent, ViewBoxAnnotatableProps } from '../../DocComponent';
import { Colors } from '../../global/globalEnums';
import { MarqueeAnnotator } from '../../MarqueeAnnotator';
import { AnchorMenu } from '../../pdf/AnchorMenu';
import { Annotation } from '../../pdf/Annotation';
import { SidebarAnnos } from '../../SidebarAnnos';
import { DocumentView } from '../DocumentView';
import { FieldView, FieldViewProps } from '../FieldView';
import { PinProps, PresBox } from '../trails';
import './MapBox.scss';
import { MapBoxInfoWindow } from './MapBoxInfoWindow';
// amongus
/**
 * MapBox architecture:
 * Main component: MapBox.tsx
 * Supporting Components: SidebarAnnos, CollectionStackingView
 *
 * MapBox is a node that extends the ViewBoxAnnotatableComponent. Similar to PDFBox and WebBox, it supports interaction between sidebar content and document content.
 * The main body of MapBox uses Google Maps API to allow location retrieval, adding map markers, pan and zoom, and open street view.
 * Dash Document architecture is integrated with Maps API: When drag and dropping documents with ExifData (gps Latitude and Longitude information) available,
 * sidebarAddDocument function checks if the document contains lat & lng information, if it does, then the document is added to both the sidebar and the infowindow (a pop up corresponding to a map marker--pin on map).
 * The lat and lng field of the document is filled when importing (spec see ConvertDMSToDD method and processFileUpload method in Documents.ts).
 * A map marker is considered a document that contains a collection with stacking view of documents, it has a lat, lng location, which is passed to Maps API's custom marker (red pin) to be rendered on the google maps
 */

// const _global = (window /* browser */ || global /* node */) as any;

const mapContainerStyle = {
    height: '100%',
};

const defaultCenter = {
    lat: 42.360081,
    lng: -71.058884,
};

const mapOptions = {
    fullscreenControl: false,
};

const bingApiKey = process.env.BING_MAPS; // if you're running local, get a Bing Maps api key here: https://www.bingmapsportal.com/  and then add it to the .env file in the Dash-Web root directory as: _CLIENT_BING_MAPS=<your apikey>

/**
 * Consider integrating later: allows for drawing, circling, making shapes on map
 */
// const drawingManager = new window.google.maps.drawing.DrawingManager({
//     drawingControl: true,
//     drawingControlOptions: {
//         position: google.maps.ControlPosition.TOP_RIGHT,
//         drawingModes: [
//             google.maps.drawing.OverlayType.MARKER,
//             // currently we are not supporting the following drawing mode on map, a thought for future development
//             google.maps.drawing.OverlayType.CIRCLE,
//             google.maps.drawing.OverlayType.POLYLINE,
//         ],
//     },
// });

// options for searchbox in Google Maps Places Autocomplete API
const options = {
    fields: ['formatted_address', 'geometry', 'name'], // note: level of details is charged by item per retrieval, not recommended to return all fields
    strictBounds: false,
    types: ['establishment'], // type pf places, subject of change according to user need
} as google.maps.places.AutocompleteOptions;

@observer
export class MapBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatableProps & FieldViewProps & Partial<GoogleMapProps>>() {
    private _dropDisposer?: DragManager.DragDropDisposer;
    private _disposers: { [name: string]: IReactionDisposer } = {};
    private _annotationLayer: React.RefObject<HTMLDivElement> = React.createRef();
    @observable private _overlayAnnoInfo: Opt<Doc>;
    showInfo = action((anno: Opt<Doc>) => (this._overlayAnnoInfo = anno));
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(MapBox, fieldKey);
    }
    public get SidebarKey() {
        return this.fieldKey + '_sidebar';
    }
    private _setPreviewCursor: undefined | ((x: number, y: number, drag: boolean, hide: boolean) => void);
    @computed get inlineTextAnnotations() {
        return this.allMapMarkers.filter(a => a.textInlineAnnotations);
    }

    @observable private _map: google.maps.Map = null as unknown as google.maps.Map;
    @observable private selectedPlace: Doc | undefined;
    @observable private markerMap: { [id: string]: google.maps.Marker } = {};
    @observable private center = navigator.geolocation ? navigator.geolocation.getCurrentPosition : defaultCenter;
    @observable private _marqueeing: number[] | undefined;
    @observable private inputRef = React.createRef<HTMLInputElement>();
    @observable private searchMarkers: google.maps.Marker[] = [];
    // @observable private searchBox = new window.google.maps.places.Autocomplete(this.inputRef.current!, options);
    @observable private _savedAnnotations = new ObservableMap<number, HTMLDivElement[]>();
    @computed get allSidebarDocs() {
        return DocListCast(this.dataDoc[this.SidebarKey]);
    }
    @computed get allMapMarkers() {
        return DocListCast(this.dataDoc[this.annotationKey]);
    }
    @observable private toggleAddMarker = false;
    private _mainCont: React.RefObject<HTMLDivElement> = React.createRef();

    @observable _showSidebar = false;
    @computed get SidebarShown() {
        return this._showSidebar || this.layoutDoc._layout_showSidebar ? true : false;
    }

    static _canAnnotate = true;
    static _hadSelection: boolean = false;
    private _sidebarRef = React.createRef<SidebarAnnos>();
    private _ref: React.RefObject<HTMLDivElement> = React.createRef();
    private _disposer: {[key:string]:IReactionDisposer} = {}
    componentDidMount() {
        this.props.setContentView?.(this);
        this._disposer.location = reaction(() => ({lat:this.rootDoc.latitude, lng:this.rootDoc.longitude, zoom:this.rootDoc.zoom,mapType:this.rootDoc.mapType}), 
        (locationObject) => {

            this._bingMap.current.setView({
                mapTypeId: locationObject.mapType,
                zoom:locationObject.zoom,
                center: new this.MicrosoftMaps.Location(locationObject.lat, locationObject.lng),
            });

        }, {fireImmediately: true});
        // this._disposer.pins = reaction(() => ({pinList:this.dataDoc[this.annotationKey]}), 
        // (pinsObject) => {
        //     this._bingMap.current.entities.clear();
        //     pinsObject.pinList.map((pushpin: Doc) => (
        //                         <DocumentView
        //                             {...this.props}
        //                             Document={pushpin}
        //                             DataDoc={undefined}
        //                             PanelWidth={returnOne}
        //                             PanelHeight={returnOne}
        //                             NativeWidth={returnOne} 
        //                             NativeHeight={returnOne}
        //                             onClick={()=>new ScriptField(undefined)}
        //                             onKey={undefined}
        //                             onDoubleClick={undefined}
        //                             onBrowseClick={undefined}
        //                             docFilters={returnEmptyDoclist}
        //                             docRangeFilters={returnEmptyDoclist}
        //                             searchFilterDocs={returnEmptyDoclist}
        //                             isDocumentActive={returnFalse}
        //                             isContentActive={returnFalse}
        //                             addDocTab={returnFalse}
        //                             ScreenToLocalTransform={()=>new Transform(0,0,0)}
        //                             fitContentsToBox={undefined}
        //                             focus={returnOne}
        //                 />));

        // }, {fireImmediately: false});

        
    }

    componentWillUnmount(): void {
        Object.keys(this._disposer).forEach(key => this._disposer[key]?.())
    }
    // iterate allMarkers to size, center, and zoom map to contain all markers
    private fitBounds = (map: google.maps.Map) => {
        const curBounds = map.getBounds() ?? new window.google.maps.LatLngBounds();
        const isFitting = this.allMapMarkers.reduce((fits, place) => fits && curBounds?.contains({ lat: NumCast(place.lat), lng: NumCast(place.lng) }), true as boolean);
        !isFitting && map.fitBounds(this.allMapMarkers.reduce((bounds, place) => bounds.extend({ lat: NumCast(place.lat), lng: NumCast(place.lng) }), new window.google.maps.LatLngBounds()));
    };

    /**
     * Custom control for add marker button
     * @param controlDiv
     * @param map
     */
    private CenterControl = () => {
        const controlDiv = document.createElement('div');
        controlDiv.className = 'mapBox-addMarker';
        // Set CSS for the control border.
        const controlUI = document.createElement('div');
        controlUI.style.backgroundColor = '#fff';
        controlUI.style.borderRadius = '3px';
        controlUI.style.cursor = 'pointer';
        controlUI.style.marginTop = '10px';
        controlUI.style.borderRadius = '4px';
        controlUI.style.marginBottom = '22px';
        controlUI.style.textAlign = 'center';
        controlUI.style.position = 'absolute';
        controlUI.style.width = '32px';
        controlUI.style.height = '32px';
        controlUI.title = 'Click to toggle marker mode.  In marker mode, click on map to place a marker.';

        const plIcon = document.createElement('img');
        plIcon.src = 'https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/add-256.png';
        plIcon.style.color = 'rgb(25,25,25)';
        plIcon.style.fontFamily = 'Roboto,Arial,sans-serif';
        plIcon.style.fontSize = '16px';
        plIcon.style.lineHeight = '32px';
        plIcon.style.left = '18';
        plIcon.style.top = '15';
        plIcon.style.position = 'absolute';
        plIcon.width = 14;
        plIcon.height = 14;
        plIcon.innerHTML = 'Add';
        controlUI.appendChild(plIcon);

        // Set CSS for the control interior.
        const markerIcon = document.createElement('img');
        markerIcon.src = 'https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678111-map-marker-1024.png';
        markerIcon.style.color = 'rgb(25,25,25)';
        markerIcon.style.fontFamily = 'Roboto,Arial,sans-serif';
        markerIcon.style.fontSize = '16px';
        markerIcon.style.lineHeight = '32px';
        markerIcon.style.left = '-2';
        markerIcon.style.top = '1';
        markerIcon.width = 30;
        markerIcon.height = 30;
        markerIcon.style.position = 'absolute';
        markerIcon.innerHTML = 'Add';
        controlUI.appendChild(markerIcon);

        // Setup the click event listeners
        controlUI.addEventListener('click', () => {
            if (this.toggleAddMarker === true) {
                this.toggleAddMarker = false;
                console.log('add marker button status:' + this.toggleAddMarker);
                controlUI.style.backgroundColor = '#fff';
                markerIcon.style.color = 'rgb(25,25,25)';
            } else {
                this.toggleAddMarker = true;
                console.log('add marker button status:' + this.toggleAddMarker);
                controlUI.style.backgroundColor = '#4476f7';
                markerIcon.style.color = 'rgb(255,255,255)';
            }
        });
        controlDiv.appendChild(controlUI);
        return controlDiv;
    };
    /**
     * Load and render all map markers
     * @param marker
     * @param place
     */
    @action
    private markerLoadHandler = (marker: google.maps.Marker, place: Doc) => {
        place[Id] ? (this.markerMap[place[Id]] = marker) : null;
    };

    /**
     * on clicking the map marker, set the selected place to the marker document & set infowindowopen to be true
     * @param e
     * @param place
     */
    @action
    private markerClickHandler = (e: google.maps.MapMouseEvent, place: Doc) => {
        // set which place was clicked
        this.selectedPlace = place;
        // place.infoWindowOpen = true;
    };

    /**
     * Place the marker on google maps & store the empty marker as a MapMarker Document in allMarkers list
     * @param position - the LatLng position where the marker is placed
     * @param map
     */
    @action
    private placeMarker = (position: google.maps.LatLng, map: google.maps.Map) => {
        const marker = new google.maps.Marker({
            position: position,
            map: map,
        });
        map.panTo(position);
        const mapMarker = Docs.Create.PushpinDocument(NumCast(position.lat()), NumCast(position.lng()), false, [], {});
        this.addDocument(mapMarker, this.annotationKey);
    };

    _loadPending = true;
    /**
     * store a reference to google map instance
     * setup the drawing manager on the top right corner of map
     * fit map bounds to contain all markers
     * @param map
     */
    @action
    private loadHandler = (map: google.maps.Map) => {
        this._map = map;
        this._loadPending = true;
        const centerControlDiv = this.CenterControl();
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(centerControlDiv);
        //drawingManager.setMap(map);
        // if (navigator.geolocation) {
        //     navigator.geolocation.getCurrentPosition(
        //         (position: Position) => {
        //             const pos = {
        //                 lat: position.coords.latitude,
        //                 lng: position.coords.longitude,
        //             };
        //             this._map.setCenter(pos);
        //         }
        //     );
        // } else {
        //     alert("Your geolocation is not supported by browser.")
        // };
        map.setZoom(NumCast(this.dataDoc.mapZoom, 2.5));
        map.setCenter(new google.maps.LatLng(NumCast(this.dataDoc.mapLat), NumCast(this.dataDoc.mapLng)));
        setTimeout(() => {
            if (this._loadPending && this._map.getBounds()) {
                this._loadPending = false;
                this.layoutDoc.freeform_fitContentsToBox && this.fitBounds(this._map);
            }
        }, 250);
        // listener to addmarker event
        this._map.addListener('click', (e: MouseEvent) => {
            if (this.toggleAddMarker === true) {
                this.placeMarker((e as any).latLng, map);
            }
        });
    };

    @action
    centered = () => {
        if (this._loadPending && this._map.getBounds()) {
            this._loadPending = false;
            this.layoutDoc.freeform_fitContentsToBox && this.fitBounds(this._map);
        }
        this.dataDoc.mapLat = this._map.getCenter()?.lat();
        this.dataDoc.mapLng = this._map.getCenter()?.lng();
    };

    @action
    zoomChanged = () => {
        if (this._loadPending && this._map.getBounds()) {
            this._loadPending = false;
            this.layoutDoc.freeform_fitContentsToBox && this.fitBounds(this._map);
        }
        this.dataDoc.mapZoom = this._map.getZoom();
    };

    /**
     * function that reads the place inputed from searchbox, then zoom in on the location that's been autocompleted;
     * add a customized temporary marker on the map
     */
    @action
    private handlePlaceChanged = () => {
        const place = this.searchBox.getPlace();

        if (!place.geometry || !place.geometry.location) {
            // user entered the name of a place that wasn't suggested & pressed the enter key, or place details request failed
            window.alert("No details available for input: '" + place.name + "'");
            return;
        }

        // zoom in on the location of the search result
        if (place.geometry.viewport) {
            this._map.fitBounds(place.geometry.viewport);
        } else {
            this._map.setCenter(place.geometry.location);
            this._map.setZoom(17);
        }

        // customize icon => customized icon for the nature of the location selected
        const icon = {
            url: place.icon as string,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25),
        };

        // put temporary cutomized marker on searched location
        this.searchMarkers.forEach(marker => {
            marker.setMap(null);
        });
        this.searchMarkers = [];
        this.searchMarkers.push(
            new window.google.maps.Marker({
                map: this._map,
                icon,
                title: place.name,
                position: place.geometry.location,
            })
        );
    };

    /**
     * Called when dragging documents into map sidebar or directly into infowindow; to create a map marker, ref to MapMarkerDocument in Documents.ts
     * @param doc
     * @param sidebarKey
     * @returns
     */
    sidebarAddDocument = (doc: Doc | Doc[], sidebarKey?: string) => {
        console.log('print all sidebar Docs');
        if (!this.layoutDoc._layout_showSidebar) this.toggleSidebar();
        const docs = doc instanceof Doc ? [doc] : doc;
        docs.forEach(doc => {
            if (doc.lat !== undefined && doc.lng !== undefined) {
                const existingMarker = this.allMapMarkers.find(marker => marker.lat === doc.lat && marker.lng === doc.lng);
                if (existingMarker) {
                    Doc.AddDocToList(existingMarker, 'data', doc);
                } else {
                    const marker = Docs.Create.PushpinDocument(NumCast(doc.lat), NumCast(doc.lng), false, [doc], {});
                    this.addDocument(marker, this.annotationKey);
                }
            }
        }); //add to annotation list

        return this.addDocument(doc, sidebarKey); // add to sidebar list
    };

    /**
     * Removing documents from the sidebar
     * @param doc
     * @param sidebarKey
     * @returns
     */
    sidebarRemoveDocument = (doc: Doc | Doc[], sidebarKey?: string) => {
        if (this.layoutDoc._layout_showSidebar) this.toggleSidebar();
        const docs = doc instanceof Doc ? [doc] : doc;
        return this.removeDocument(doc, sidebarKey);
    };

    /**
     * Toggle sidebar onclick the tiny comment button on the top right corner
     * @param e
     */
    sidebarBtnDown = (e: React.PointerEvent) => {
        setupMoveUpEvents(
            this,
            e,
            (e, down, delta) =>
                runInAction(() => {
                    const localDelta = this.props
                        .ScreenToLocalTransform()
                        .scale(this.props.NativeDimScaling?.() || 1)
                        .transformDirection(delta[0], delta[1]);
                    const fullWidth = this.layoutDoc[Width]();
                    const mapWidth = fullWidth - this.sidebarWidth();
                    if (this.sidebarWidth() + localDelta[0] > 0) {
                        this._showSidebar = true;
                        this.layoutDoc._width = fullWidth + localDelta[0];
                        this.layoutDoc._layout_sidebarWidthPercent = ((100 * (this.sidebarWidth() + localDelta[0])) / (fullWidth + localDelta[0])).toString() + '%';
                    } else {
                        this._showSidebar = false;
                        this.layoutDoc._width = mapWidth;
                        this.layoutDoc._layout_sidebarWidthPercent = '0%';
                    }
                    return false;
                }),
            emptyFunction,
            () => UndoManager.RunInBatch(this.toggleSidebar, 'toggle sidebar map')
        );
    };

    sidebarWidth = () => (Number(this.layout_sidebarWidthPercent.substring(0, this.layout_sidebarWidthPercent.length - 1)) / 100) * this.props.PanelWidth();
    @computed get layout_sidebarWidthPercent() {
        return StrCast(this.layoutDoc._layout_sidebarWidthPercent, '0%');
    }
    @computed get sidebarColor() {
        return StrCast(this.layoutDoc.sidebarColor, StrCast(this.layoutDoc[this.props.fieldKey + '_backgroundColor'], '#e4e4e4'));
    }

    /**
     * Handles toggle of sidebar on click the little comment button
     */
    @computed get sidebarHandle() {
        return (
            <div
                className="mapBox-overlayButton-sidebar"
                key="sidebar"
                title="Toggle Sidebar"
                style={{
                    display: !this.props.isContentActive() ? 'none' : undefined,
                    top: StrCast(this.rootDoc._layout_showTitle) === 'title' ? 20 : 5,
                    backgroundColor: this.SidebarShown ? Colors.MEDIUM_BLUE : Colors.BLACK,
                }}
                onPointerDown={this.sidebarBtnDown}>
                <FontAwesomeIcon style={{ color: Colors.WHITE }} icon={'comment-alt'} size="sm" />
            </div>
        );
    }

    // TODO: Adding highlight box layer to Maps
    @action
    toggleSidebar = () => {
        //1.2 * w * ? = .2 * w      .2/1.2
        const prevWidth = this.sidebarWidth();
        this.layoutDoc._layout_showSidebar = (this.layoutDoc._layout_sidebarWidthPercent = StrCast(this.layoutDoc._layout_sidebarWidthPercent, '0%') === '0%' ? `${(100 * 0.2) / 1.2}%` : '0%') !== '0%';
        this.layoutDoc._width = this.layoutDoc._layout_showSidebar ? NumCast(this.layoutDoc._width) * 1.2 : Math.max(20, NumCast(this.layoutDoc._width) - prevWidth);
    };

    sidebarDown = (e: React.PointerEvent) => {
        setupMoveUpEvents(this, e, this.sidebarMove, emptyFunction, () => setTimeout(this.toggleSidebar), true);
    };
    sidebarMove = (e: PointerEvent, down: number[], delta: number[]) => {
        const bounds = this._ref.current!.getBoundingClientRect();
        this.layoutDoc._layout_sidebarWidthPercent = '' + 100 * Math.max(0, 1 - (e.clientX - bounds.left) / bounds.width) + '%';
        this.layoutDoc._layout_showSidebar = this.layoutDoc._layout_sidebarWidthPercent !== '0%';
        e.preventDefault();
        return false;
    };

    setPreviewCursor = (func?: (x: number, y: number, drag: boolean, hide: boolean) => void) => (this._setPreviewCursor = func);

    @action
    onMarqueeDown = (e: React.PointerEvent) => {
        if (!e.altKey && e.button === 0 && this.props.isContentActive(true) && ![InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) {
            setupMoveUpEvents(
                this,
                e,
                action(e => {
                    MarqueeAnnotator.clearAnnotations(this._savedAnnotations);
                    this._marqueeing = [e.clientX, e.clientY];
                    return true;
                }),
                returnFalse,
                () => MarqueeAnnotator.clearAnnotations(this._savedAnnotations),
                false
            );
        }
    };
    @action finishMarquee = (x?: number, y?: number) => {
        this._marqueeing = undefined;
        x !== undefined && y !== undefined && this._setPreviewCursor?.(x, y, false, false);
    };

    addDocumentWrapper = (doc: Doc | Doc[], annotationKey?: string) => {
        return this.addDocument(doc, annotationKey);
    };

    pointerEvents = () => {
        return this.props.isContentActive() && this.props.pointerEvents?.() !== 'none' && !MarqueeOptionsMenu.Instance.isShown() ? 'all' : SnappingManager.GetIsDragging() ? undefined : 'none';
    };
    @computed get annotationLayer() {
        return (
            <div className="mapBox-annotationLayer" style={{ height: Doc.NativeHeight(this.Document) || undefined }} ref={this._annotationLayer}>
                {this.inlineTextAnnotations
                    .sort((a, b) => NumCast(a.y) - NumCast(b.y))
                    .map(anno => (
                        <Annotation key={`${anno[Id]}-annotation`} {...this.props} fieldKey={this.annotationKey} pointerEvents={this.pointerEvents} showInfo={this.showInfo} dataDoc={this.dataDoc} anno={anno} />
                    ))}
            </div>
        );
    }

    // Old get anchor function
    // getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => AnchorMenu.Instance?.GetAnchor(this._savedAnnotations, addAsAnnotation) ?? this.rootDoc;

    /**
     * render contents in allMapMarkers (e.g. images with exifData) into google maps as map marker
     * @returns
     */
    private renderMarkers = () => {
        return this.allMapMarkers.map(place => (
            <Marker key={place[Id]} position={{ lat: NumCast(place.lat), lng: NumCast(place.lng) }} onLoad={marker => this.markerLoadHandler(marker, place)} onClick={(e: google.maps.MapMouseEvent) => this.markerClickHandler(e, place)} />
        ));
    };

    // TODO: auto center on select a document in the sidebar
    private handleMapCenter = (map: google.maps.Map) => {
        // console.log("print the selected views in selectionManager:")
        // if (SelectionManager.Views().lastElement()) {
        //     console.log(SelectionManager.Views().lastElement());
        // }
    };

    panelWidth = () => this.props.PanelWidth() / (this.props.NativeDimScaling?.() || 1) - this.sidebarWidth();
    panelHeight = () => this.props.PanelHeight() / (this.props.NativeDimScaling?.() || 1);
    scrollXf = () => this.props.ScreenToLocalTransform().translate(0, NumCast(this.layoutDoc._layout_scrollTop));
    transparentFilter = () => [...this.props.docFilters(), Utils.IsTransparentFilter()];
    opaqueFilter = () => [...this.props.docFilters(), Utils.IsOpaqueFilter()];
    infoWidth = () => this.props.PanelWidth() / 5;
    infoHeight = () => this.props.PanelHeight() / 5;
    anchorMenuClick = () => this._sidebarRef.current?.anchorMenuClick;
    savedAnnotations = () => this._savedAnnotations;

    _bingSearchManager: any;
    _bingMap: any;
    get MicrosoftMaps() {
        return (window as any).Microsoft.Maps;
    }
    // uses Bing Search to retrieve lat/lng for a location.  eg.,
    //   const results = this.geocodeQuery(map.map, 'Philadelphia, PA');
    // to move the map to that location:
    //     const location = await this.geocodeQuery(this._bingMap, 'Philadelphia, PA');
    //     this._bingMap.current.setView({
    //        mapTypeId: this.MicrosoftMaps.MapTypeId.aerial,
    //        center: new this.MicrosoftMaps.Location(loc.latitude, loc.longitude),
    //     });
    //
    bingGeocode = (map: any, query: string) => {
        return new Promise<{ latitude: number; longitude: number }>((res, reject) => {
            //If search manager is not defined, load the search module.
            if (!this._bingSearchManager) {
                //Create an instance of the search manager and call the geocodeQuery function again.
                this.MicrosoftMaps.loadModule('Microsoft.Maps.Search', () => {
                    this._bingSearchManager = new this.MicrosoftMaps.Search.SearchManager(map.current);
                    res(this.bingGeocode(map, query));
                });
            } else {
                this._bingSearchManager.geocode({
                    where: query,
                    callback: action((r: any) => {
                        res(r.results[0].location);
                    }),
                    errorCallback: (e: any) => reject(),
                });
            }
        });
    };

    /**
     *
     *
     *  ERIC'S BING MAP CODE BELOW
     *
     *
     *
     **/

    bingSearchBarContents: any = 'Boston, MA'; // For Bing Maps: The contents of the Bing search bar (string)

    geoDataRequestOptions = {
        entityType: 'PopulatedPlace',
    };

    
    // incrementer: number = 0;
    /*
     * Creates Pushpin doc and adds it to the list of annotations
     */
    @action
    createPushpin = (latitude: number, longitude: number) => {
        // Stores the pushpin as a MapMarkerDocument
        const mapMarker = Docs.Create.PushpinDocument(NumCast(latitude), NumCast(longitude), false, [], {}
        // ,'pushpinIDamongus'+ this.incrementer++
        );
        this.addDocument(mapMarker, this.annotationKey);

        // mapMarker.infoWindowOpen = true;
    };

    /*
     * Pushpin dblclick
     */
    @action
    pushpinDblClicked = (pinDoc:Doc,pin:any) => {
        this.removePushpin(pinDoc,pin);
    };
    /*
     * Pushpin onclick
     */
    @action
    pushpinClicked = (pinDoc:Doc,pin:any) => {
        // TODO:
        // if (sidebarannos is not open) open sidebarannos
        // creates button onclick removes the doc from annotations

        // pan to pushpin location
        this.dataDoc.latitude = pinDoc.lat;
        this.dataDoc.longitude = pinDoc.lng;

        


    //     @action
    // onPointerDown = (e: React.PointerEvent) => {
    //     if (e.button === 2 || e.ctrlKey) {
    //         AnchorMenu.Instance.Status = 'annotation';
    //         AnchorMenu.Instance.Delete = this.deleteAnnotation.bind(this);
    //         AnchorMenu.Instance.Pinned = false;
    //         AnchorMenu.Instance.PinToPres = this.pinToPres;
    //         AnchorMenu.Instance.MakeTargetToggle = this.makeTargretToggle;
    //         AnchorMenu.Instance.IsTargetToggler = this.isTargetToggler;
    //         AnchorMenu.Instance.ShowTargetTrail = () => this.showTargetTrail(this.annoTextRegion);
    //         AnchorMenu.Instance.jumpTo(e.clientX, e.clientY, true);
    //         e.stopPropagation();
    //     } else if (e.button === 0) {
    //         e.stopPropagation();
    //         LinkFollower.FollowLink(undefined, this.annoTextRegion, false);
    //     }
    // };

        // TODO: UPDATE FOR DASHDOC SELECTION
    };

    /**
     * Returns a list of Pushpin docs
     */
    @computed get allMapPushpins() {
        return DocListCast(this.dataDoc[this.annotationKey]);
    }

    /**
     * Map OnClick ~> creates a pushpin
     */
    @action
    mapOnClick = (e: { location: { latitude: any; longitude: any } }) => {
        if (this.placePinOn) {
            this.createPushpin(e.location.latitude, e.location.longitude);
            // this.addAllPins();
            this.placePinOn = false;
        }
    };


    

    /*
     * Updates values of layout doc to match the current map
     */
    @action
    updateLayout = () => {
            this.dataDoc.latitude = this._bingMap.current.getCenter().latitude;
            this.dataDoc.longitude = this._bingMap.current.getCenter().longitude;
            this.dataDoc.zoom = this._bingMap.current.getZoom();
            // if(this.dataDoc.mapType == 'x'){
            //     this.dataDoc.locationToLookAt
            // }
            // this.dataDoc.mapType = new this.MicrosoftMaps.MapTypeId();
    };
    /*
     * Updates maptype
     */
    @action
    updateMapType = () => {
            this.dataDoc.mapType = this._bingMap.current.getMapTypeId();

    };


    searched_pin: any;
    /*
     * For Bing Maps
     * Called by search button's onClick
     * Finds the geocode of the searched contents and sets location to that location
     **/
    @action
    bingSearch = async () => {
        const location = await this.bingGeocode(this._bingMap, this.bingSearchBarContents);
        this.dataDoc.latitude = location.latitude;
        this.dataDoc.longitude = location.longitude;
        this.dataDoc.zoom = this._bingMap.current.getZoom();
        // this.dataDoc.mapType = this._bingMap.current.getMapTypeId();
        // this.bingSearchBarContents=location.name;

        // Centers on the searched location
        // this._bingMap.current.panTo(new this.MicrosoftMaps.Location(this.dataDoc.latitude, this.dataDoc.longitude));

        // this._bingMap.current.setView({
        //     center: new this.MicrosoftMaps.Location(this.dataDoc.latitude, this.dataDoc.longitude),
        // });
        
        

        
        // Creates a temporary pin but does not add it to the dataDoc
        var temp = new this.MicrosoftMaps.Pushpin(new this.MicrosoftMaps.Location(location.latitude, location.longitude), {
            color: 'blue',
        });
        if (temp != this.searched_pin || this.searched_pin == null) {
            this._bingMap.current.entities.push(temp);
            this.searched_pin = temp;
        }

    };

    /**
     * Adds all pushpins in dataDoc onto the map (render) - OLD & UNUSED
     */
    // @action
    // addAllPins = () => {
    //     this._bingMap.current.entities.clear();
    //     if (this.searched_pin) this._bingMap.current.entities.push(this.searched_pin);
    //     // this.allMapPushpins.map(pin => this.addPushpin(pin));
    // };

    /*
     * Returns doc w/ relevant info
     */
    getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => {
        const anchor =
            Docs.Create.MapanchorDocument({
                title: 'MapAnchor:' + this.rootDoc.title,
                presLat: NumCast(this.dataDoc.latitude),
                presLong: NumCast(this.dataDoc.longitude),
                presZoom: NumCast(this.dataDoc.zoom),
                presMapType: this.dataDoc.mapType,
                // preslocationToLookAt:this.dataDoc.locationToLookAt,
                // presType: 
                unrendered: true,
                annotationOn: this.rootDoc,
            });
        if (anchor) {
            if (!addAsAnnotation) anchor.backgroundColor = 'transparent';
            /* addAsAnnotation &&*/ this.addDocument(anchor);
            PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}), map: true } }, this.rootDoc);
            return anchor;
        }
        return this.rootDoc;
    };

    /*
    *   Input: pin doc
    *   Adds MicrosoftMaps Pushpin to the map (render)
    */
    @action
    addPushpin = (pin: Doc) => {
        const pushPin = pin.infoWindowOpen ? new this.MicrosoftMaps.Pushpin(new this.MicrosoftMaps.Location(pin.lat, pin.lng), {}): new this.MicrosoftMaps.Pushpin(new this.MicrosoftMaps.Location(pin.lat, pin.lng), 
        // {icon: 'http://icons.iconarchive.com/icons/icons-land/vista-map-markers/24/Map-Marker-Marker-Outside-Chartreuse-icon.png'}
        );

        
        this._bingMap.current.entities.push(pushPin);

        this.MicrosoftMaps.Events.addHandler(pushPin, 'click', (e: any) => this.pushpinClicked(pin,pushPin));
        this.MicrosoftMaps.Events.addHandler(pushPin, 'dblclick', (e: any) => this.pushpinDblClicked(pin,pushPin));
    }



    @observable
    pinIsSelected_TEMPORARY:boolean=false; // toggles if remove pin button appears

    /*
    *   Input: pin doc
    *   Removes MicrosoftMaps Pushpin to the map (render)
    */
    @action
    removePushpin = (pinDoc:Doc,pin:any)=>{
        // this.allMapPushpins
        // this.allMapPushpins.map(pin => this.addPushpin(pin));
        // this._bingMap.current.entities.clear();
        this._bingMap.current.entities.remove(pin);
        this.removeDocument(pinDoc, this.annotationKey);

        // this.dataDoc[this.annotationKey]
    }

    /**
     * View options for bing maps
     */
    bingViewOptions = {
        center: { latitude: this.dataDoc.latitude ?? defaultCenter.lat, longitude: this.dataDoc.longitude ?? defaultCenter.lng },
        zoom: this.dataDoc.latitude ?? 10,
        mapTypeId: 'grayscale',
    };

    /**
     * Map options
     */
    bingMapOptions = {
        navigationBarMode: 'compact',
        backgroundColor: '#f1f3f4',
        enableInertia: true,
        supportedMapTypes:['grayscale', 'canvasLight'],
        disableMapTypeSelectorMouseOver :true,
        // showScalebar:true
        // disableRoadView:true,
        // disableBirdseye:true
        streetsideOptions:{
            showProblemReporting:false,
            showCurrentAddress:false,
        },
    };

    /**
     * Toggles mode for placing a pin down on map
     */
    @observable
    placePinOn: boolean | undefined;
    @action
    togglePlacePin = () => {
        if (this.placePinOn) this.placePinOn = false;
        else this.placePinOn = true;
    };

    /*
     * Called when BingMap is first rendered 
     * Initializes starting values
     */
    bingMapReady = (map: any) => {
        this._bingMap = map.map;
        this.MicrosoftMaps.Events.addHandler(this._bingMap.current, 'click', this.mapOnClick);
        this.MicrosoftMaps.Events.addHandler(this._bingMap.current, 'viewchangeend', this.updateLayout);
        this.MicrosoftMaps.Events.addHandler(this._bingMap.current, 'maptypechanged', this.updateMapType);
        this.updateLayout();
        this.updateMapType();
    }
        
    render() {
        const renderAnnotations = (docFilters?: () => string[]) => null;
        return (
            <div className="mapBox" ref={this._ref}>
                <div
                    className="mapBox-wrapper"
                    onWheel={e => e.stopPropagation()}
                    onPointerDown={async e => {
                        e.button === 0 && !e.ctrlKey && e.stopPropagation();
                        // just a simple test of bing maps geocode api
                        // const loc = await this.bingGeocode(this._bingMap, 'Philadelphia, PA');
                        // this._bingMap.current.setView({
                        //     mapTypeId: this.MicrosoftMaps.MapTypeId.aerial,
                        //     center: new this.MicrosoftMaps.Location(loc.latitude, loc.longitude),
                        //     zoom: 15,
                        // });
                    }}
                    style={{ width: `calc(100% - ${this.layout_sidebarWidthPercent})`, pointerEvents: this.pointerEvents() }}>
                    <div style={{ mixBlendMode: 'multiply' }}>{renderAnnotations(this.transparentFilter)}</div>
                    {renderAnnotations(this.opaqueFilter)}
                    {SnappingManager.GetIsDragging() ? null : renderAnnotations()}
                    {this.annotationLayer}

                    <EditableText setEditing={(isEditing: boolean) => ({})} editing onEdit={(newText: string) => (this.bingSearchBarContents = newText)} placeholder="..." text="Boston, MA" />

                    <input type="button" value="Search" onClick={this.bingSearch} />

                    {this.placePinOn ? <input type="button" value="Place Pin Mode On" onClick={this.togglePlacePin} /> : <input type="button" value="Place Pin Mode Off" onClick={this.togglePlacePin} />}
                    {/* {this.pinIsSelected_TEMPORARY? <input type="button" value="Delete Pin" onClick={this.removeSelectedPin} /> : null} */}
                    <BingMapsReact onMapReady={this.bingMapReady} bingMapsKey={bingApiKey} height="100%" mapOptions={this.bingMapOptions} width="100%" viewOptions={this.bingViewOptions}>
                    </BingMapsReact>
                    <div>
                        
                        {this.allMapPushpins
                            .map(pushpin => (
                                <DocumentView
                                    {...this.props}
                                    Document={pushpin}
                                    DataDoc={undefined}
                                    PanelWidth={returnOne}
                                    PanelHeight={returnOne}
                                    NativeWidth={returnOne} 
                                    NativeHeight={returnOne}
                                    onClick={()=>new ScriptField(undefined)}
                                    onKey={undefined}
                                    onDoubleClick={undefined}
                                    onBrowseClick={undefined}
                                    docFilters={returnEmptyDoclist}
                                    docRangeFilters={returnEmptyDoclist}
                                    searchFilterDocs={returnEmptyDoclist}
                                    isDocumentActive={returnFalse}
                                    isContentActive={returnFalse}
                                    addDocTab={returnFalse}
                                    ScreenToLocalTransform={()=>new Transform(0,0,0)}
                                    fitContentsToBox={undefined}
                                    focus={returnOne}
                        />
                            ))}
                    </div>
                    {/* <MapBoxInfoWindow
                                    key={Docs.Create.MapMarkerDocument(NumCast(40), NumCast(40), false, [], {})[Id]}
                                    {...OmitKeys(this.props, ['NativeWidth', 'NativeHeight', 'setContentView']).omit}
                                    place={Docs.Create.MapMarkerDocument(NumCast(40), NumCast(40), false, [], {})}
                                    markerMap={this.markerMap}
                                    PanelWidth={this.infoWidth}
                                    PanelHeight={this.infoHeight}
                                    moveDocument={this.moveDocument}
                                    isAnyChildContentActive={this.isAnyChildContentActive}
                                    whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
                                /> */}

                    {!this._marqueeing || !this._mainCont.current || !this._annotationLayer.current ? null : (
                        <MarqueeAnnotator
                            rootDoc={this.rootDoc}
                            anchorMenuClick={this.anchorMenuClick}
                            scrollTop={0}
                            down={this._marqueeing}
                            scaling={returnOne}
                            addDocument={this.addDocumentWrapper}
                            docView={this.props.docViewPath().lastElement()}
                            finishMarquee={this.finishMarquee}
                            savedAnnotations={this.savedAnnotations}
                            annotationLayer={this._annotationLayer.current}
                            selectionText={returnEmptyString}
                            mainCont={this._mainCont.current}
                        />
                    )}
                </div>
                {/* </LoadScript > */}
                <div className="mapBox-sidebar" style={{ width: `${this.layout_sidebarWidthPercent}`, backgroundColor: `${this.sidebarColor}` }}>
                    <SidebarAnnos
                        ref={this._sidebarRef}
                        {...this.props}
                        fieldKey={this.fieldKey}
                        rootDoc={this.rootDoc}
                        layoutDoc={this.layoutDoc}
                        dataDoc={this.dataDoc}
                        usePanelWidth={true}
                        showSidebar={this.SidebarShown}
                        nativeWidth={NumCast(this.layoutDoc._nativeWidth)}
                        whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
                        PanelWidth={this.sidebarWidth}
                        sidebarAddDocument={this.sidebarAddDocument}
                        moveDocument={this.moveDocument}
                        removeDocument={this.sidebarRemoveDocument}
                    />
                </div>
                {this.sidebarHandle}
            </div>
        );
    }
}