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

时间:2017-04-03 13:45:30

标签: angular typescript google-maps-api-3

问题

我正在尝试使用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[];
} 

The Plunkr

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

1 个答案:

答案 0 :(得分:1)

首先,感谢您使用Google地图API密钥; - )。

此处的问题是,在尝试与Google地图进行互动时,尚未加载Google地图。你需要提供一个回调来使它工作。

This question可能会有所帮助。