2016-04-27 35 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'回调中)... –