尝试在页面上呈现谷歌地图时出错



问题

我正在尝试使用Angular 2和TypeScript中的API创建Google地图的自定义实现。我已经完成了所有工作,直到地图应该在页面上呈现的部分。

遗憾的是,地图呈现为空白的灰色方块,尝试与之交互会导致非常不起眼的Cannot read property 'x' of undefined错误。

我在网站上读到过其他几个问题,这通常是由于地图试图渲染到隐藏的 DOM 元素中,加载到不存在的 DOM 元素中(不在页面加载函数中(,或者它失去了对它被渲染到的 DOM 元素的引用。

从我在这里看到的情况来看,我已经满足了所有这些条件,除非我错过了 Angular 在这里的工作方式?

有人可以在这里指出我正确的方向吗?

《守则》

declare let google: any;
/**
 * @Component: Map
 * @Section: Miscellaneous
 * @Description: Generates an interactive map
 */
@Component({
    selector: 'mymap',
    template: `<div #map style="min-width:600px; min-height: 600px;"></div>`
})
export class MyMapComponent {
    // A reference to the map DOM element
    @ViewChild("map") mapEl: ElementRef;
    // A reference to the map object
    map: any;
    // Intializes the map
    initMap: Function = function(){
        // Set the map to a new google map
        this.map = new google.maps.Map(this.mapEl.nativeElement, {
            // Default zoom level
            zoom: this.zoomLevel | 6
        })
        console.log(this.map);
    };
    // Sets the center of the map
    setMapCenter: Function = function( latlng: any ){
        if ( this.map && latlng ){
            this.map.setCenter();
        }
    }
    // Callback for the call to the browser to request the users estimated lat/lng
    getUserLocationCallback: any = function( position: any ){
        // Catches a Geoposition object:
        // coords
        //  - accuracy
        //  - altitude
        //  - altitudeAccuracy
        //  - heading
        //  - latitude
        //  - longitude
        //  - speed
        // timestamp
        this.setMapCenter(new google.maps.LatLng({lat: position.coords.latitude, lng: position.coords.latitude}));
    }
    // On Init
    ngAfterViewInit(){
        // Set the key for the Google Maps API
        var gmap_api_key = "[KEY_REMOVED]";
        // Create the script tag and add it to the document
        var gmap = document.createElement('script');
        gmap.type = 'text/javascript';
        gmap.async = true;
        gmap.src = "https://maps.googleapis.com/maps/api/js?key=" + gmap_api_key;
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(gmap, s);
        // Wait for the script to load
        var mapsInterval = setInterval( () => {
            // If the script is loaded and the maps functions are available
            if ( typeof google !== "undefined" && google.maps && google.maps.Map){
                // Clear our interval
                clearInterval(mapsInterval);
                // Initialize the map
                this.initMap();
                // Request location from the browser. Arrow function used to maintain scope.
                navigator.geolocation.getCurrentPosition( () => { this.getUserLocationCallback } );
            }
        }, 0);
    }
    /**
     * @Property: displayedMarkers
     * @Description: A list of markers current displayed on the map.
     * @Type: array
     * @Two-way: output only
     */
    @Output() displayedMarkersChange: EventEmitter<any[]> = new EventEmitter;
    /**
     * @Property: mapCenter
     * @Description: lat/long of the center of the map being displayed
     * @Type: object {lat: "N", lng: "N"}
     * @Two-way: true
     */
    @Input()
    set mapCenter( position: any ){
        // If a position was provided
        if ( typeof position !== "undefined" ){
            // Set thet map center using the provided position
            this.setMapCenter( new google.maps.LatLng (position ) );
        }
    }
    @Output() mapCenterChange: EventEmitter<any[]> = new EventEmitter;
    /**
     * @Property: zoomLevel
     * @Description: Current zoom level of the map. Accepts values between 0 (shows the entire earth) and up 21
     * @Type: array
     * @Two-way: true
     */
    @Input() zoomLevel: number;
    @Output() zoomLevelChange: EventEmitter<number> = new EventEmitter;
    /**
     * @Property: filters
     * @Description: Filters to be applied to the marker results.
     * @Type: array
     * @Two-way: false
     */
    @Input() filters: any[];
} 

普伦克尔

https://plnkr.co/edit/pIVOCSJ5eb1PUVXoEffS?p=preview

首先,感谢您的谷歌地图API密钥;-(。

您的问题是尝试与之交互时尚未加载谷歌地图。 您需要提供回调才能使其正常工作。

这个问题可能会有所帮助。

最新更新