2017-06-01 104 views
10
import { GoogleMapsAPIWrapper } from '@agm/core'; 
import { Component, Input } from '@angular/core'; 

@Component({ 
    selector: 'core-map', 
    styleUrls: [ './map.component.scss' ], 
    templateUrl: './map.component.html', 
}) 
export class MapComponent { 
    constructor(
    public gMaps: GoogleMapsAPIWrapper 
) {} 

    public markerClicked = (markerObj) => { 
    this.gMaps.setCenter({ lat: markerObj.latitude, lng: markerObj.longitude }); 
    console.log('clicked', markerObj, { lat: markerObj.latitude, lng: markerObj.longitude }); 
    } 
} 
console output: Object {lat: 42.31277, lng: -91.24892} 

也試過panTo具有相同的結果。setCenter不能在angular2-google-maps中工作

+0

能否請您提供一些這個問題的更多細節? –

回答

16

終於得到了這個工作。必須創建一個agm-map的子組件,並創建一個負載輸出,抓取本地谷歌地圖api包裝並傳遞到我的父映射組件。我希望他們這樣做,所以你可以在常規的agm-map組件中抓取gmaps api包裝。與panTo一起工作。

家長組件標記

<agm-map [latitude]='lat' [longitude]='lng' 
    [usePanning]='true'> 
    <agm-marker *ngFor='let location of locations' 
    [latitude]='location.latitude' 
    [longitude]='location.longitude' 
    [iconUrl]='location.icon' 
    (markerClick)='markerClicked(location)'></agm-marker> 
    <core-map-content (onMapLoad)='loadAPIWrapper($event)'></core-map-content> 
</agm-map> 

父組件

/** 
* Map Component 
* API Docs: https://angular-maps.com/docs/api/latest/ts/ 
*/ 
import { GoogleMapsAPIWrapper } from '@agm/core'; 
import { Component, Input } from '@angular/core'; 

declare var google:any; 

@Component({ 
    selector: 'core-map', 
    styleUrls: [ './map.component.scss' ], 
    templateUrl: './map.component.html', 
}) 
export class MapComponent { 
    @Input() lat: number; 
    @Input() lng: number; 
    @Input() locations: {}; 
    map: any; 

    constructor(
    public gMaps: GoogleMapsAPIWrapper, 
) {} 

    public loadAPIWrapper(map) { 
    this.map = map; 
    } 

    public markerClicked = (markerObj) => { 
    const position = new google.maps.LatLng(markerObj.latitude, markerObj.longitude); 
    this.map.panTo(position); 
    } 
} 

子組件

import { Component, EventEmitter, OnInit, Output } from '@angular/core'; 

import { GoogleMapsAPIWrapper } from '@agm/core'; 

@Component({ 
    selector: 'core-map-content', 
    template: '', 
}) 
export class MapContentComponent implements OnInit { 
    @Output() onMapLoad: EventEmitter<{}> = new EventEmitter<{}>(); 

    constructor(public gMaps: GoogleMapsAPIWrapper) {} 

    ngOnInit() { 
    this.gMaps.getNativeMap().then((map) => { 
     this.onMapLoad.emit(map); 
    }); 
    } 
} 
+0

沒有任何一種方式比使用子組件? –

+0

@ f.khantsis正確,這是我找到的唯一解決方案。這不是很優雅。 –

+0

我想補充一點,你不需要'gMap'注入,因爲實例將來自孩子。您也不需要將包裝添加到模塊提供程序中,只需使用'this.map'實例即可。我不確定爲什麼wrapper默認沒有被agm組件暴露出來,但顯然這是通過設計的:「當創建一個agm-map實例時,GoogleMapsAPIWraper被創建,這完全是有意的,我們每個地圖都維護一個實例。想要獲得地圖的實例,您可以創建一個自定義組件並通過構造函數注入GoogleMapsAPIWrapper。「 – cen