Angular2 - How to setup a google.maps.OverlayView? (translate JS prototype into Typescript)

后端 未结 6 1929
逝去的感伤
逝去的感伤 2020-12-10 21:12

I\'d like to create a google map component that work like that : https://jsfiddle.net/gvvy5vxz/2/

It\'s based on this : https://developers.google.com/maps/documentat

6条回答
  •  粉色の甜心
    2020-12-10 22:14

    As my code loads google maps API asynchronously, the above answers did not work for me. My problem was typescript use google variable before loaded google API.

    Here is a solution I found.

    To see async map loader code, see Load Google Maps JS API in component [Angular]

    service

    //map.service.ts
    
    import { Injectable } from '@angular/core';
    
    ...
    declare var google;    
    export let MyOverlay; // declare and use this from other ts file
    
    @Injectable({ providedIn: 'root' })
    export class MapService {
    
        private static promise;
        map: any;
    
        public static load() {
            if (!MapService.promise) {
                MapService.promise = new Promise((resolve) => {
                  //load google api asynchronously
                });
            }
    
            return MapService.promise;
        }
    
        async initMap(gmapElement, lat = -33.92, lng = 151.25) {
            return MapService.load()  
                .then((gapi) => {
                    //map init
                    this.map = new google.maps.Map(gmapElement.nativeElement, {
                       //map options
                    })
                    /*** before init MyOverlay, 
                    1. Google API should be loaded
                    2. AFTER MAP init(rendering), Overlay Object has Projection to calculate Overlay location
                    ***/
                    this.initMyOverlay()
                })
                .catch(console.log)
        }
    
        initMyOverlay(){            
            class MyOverlayCls extends google.maps.OverlayView {    
             //omitted for code readability
            }
            MyOverlay = MyOverlayCls ; //assign class to variable
        }
    
    }
    

    component

    //map.component.ts
    import { MapService, MyOverlay} from 'map.service';
    ...
    
      @ViewChild('gmap') gmapElement: any
      ...
    
      ngOnInit() {
        console.log("maps init")
        this.mapSvc.initMap(this.gmapElement).then(_ => {
    
          //At this time, google API has been loaded and assigned MyOverlay as MyOverlayCls
          let overlay= new MyOverlay(...)    
    
        })
    

提交回复
热议问题