2016-04-27 72 views
1

試圖讓Google地圖實現在Angular 2中運行。我想顯示一堆由Angular服務提供的標記。谷歌地圖和angular2的範圍問題?

我得到一個「EXCEPTION:TypeError:this.markers在[null]中是未定義的」如果你可以幫助我,這將是非常好的!

感謝 弗雷德

這是我的組件至今:

import { Component, OnInit, provide }  from 'angular2/core'; 
import { Router }       from 'angular2/router'; 

import { Marker }       from './marker'; 
import { MapService }      from './map.service'; 

@Component({ 
    selector: 'my-map', 
    providers: [MapService], 
    templateUrl: 'app/map/map.component.html', 
    styleUrls: ['app/map/map.component.css'], 
}) 

export class MapComponent implements OnInit { 
     markers: Marker[]; 
     errorMessage: string; 

    constructor(
     private _mapService: MapService 
     ) { } 

    getDecisionsGeo() { 
     this._mapService.getDecisionsGeo() 
          .subscribe(
           markers => this.markers = markers, 
           error => this.errorMessage = <any>error);      
    } 

    ngOnInit(){ 
     this.getDecisionsGeo(); 
     this.initializeMap(); 
    } 


    initializeMap() { 
     // Giving the map some options 
     var mapOptions = { 
      zoom: 13, 
      center: new google.maps.LatLng(51.2192,4.4029) 
     }; 

     // Creating the map 
     var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 


     // Looping through all the entries from the markers data 
     for(var i = 0; i < this.markers.length; i++) { 

      // Current object 
      var obj = this.markers[i]; 

      // Adding a new marker for the object 
      var marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(obj.lat,obj.lng), 
      map: map, 
      title: obj.poi.documents.meetitem_title_pop // this works, giving the marker a title with the correct title 
      }); 

      // Adding a new info window for the object 
      var clicker = addClicker(marker, obj.poi.documents.meetitem_title_pop); 


     } // end loop 


     // Adding a new click event listener for the object 
     function addClicker(marker, content) { 
      var infowindow; 
      google.maps.event.addListener(marker, 'click', function() { 

      if (infowindow) {infowindow.close();} 
      infowindow = new google.maps.InfoWindow({content: content}); 
      infowindow.open(map, marker); 

      }); 
     } 

    } 

} 

回答

0

的問題是,您加載標記異步:

ngOnInit(){ 
    this.getDecisionsGeo(); 
    this.initializeMap(); 
} 

所以initializeMap方法的結果之前調用的HTTP請求被接收。

我會重構你的代碼是這樣的:

ngOnInit(){ 
    this.getDecisionsGeo(); 
} 

getDecisionsGeo() { 
    this._mapService.getDecisionsGeo() 
       .subscribe(
       markers => { 
        this.markers = markers; 
        this.initializeMap(); 
       }, 
       error => this.errorMessage = <any>error);      
} 
+0

蒂埃裏,你的建議得到了地圖和運行!退出:)。仍不完全清楚你的建議如何工作。 NgOnit中的方法是否同步調用?我認爲他們會按順序執行,自上而下。感謝澄清這一點。 – Fred30

+0

不客氣!實際上,第一個調用是異步的。這意味着標記列表將在稍後被接收(在調用'initializeMap'之後)。您需要等待數據被接收(在'subscribe'回調中)... –