尝试在Angular 2中运行Google Maps实现。我想显示一组由Angular服务提供的标记。
我得到一个“EXCEPTION:TypeError:在[null]中未定义this.markers”如果你可以帮助我,那就太好了!
由于 佛瑞德
到目前为止,这是我的组件:
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 :(得分:0)
问题是您异步加载标记:
initializeMap
因此在收到HTTP请求的结果之前调用ngOnInit(){
this.getDecisionsGeo();
}
getDecisionsGeo() {
this._mapService.getDecisionsGeo()
.subscribe(
markers => {
this.markers = markers;
this.initializeMap();
},
error => this.errorMessage = <any>error);
}
方法。
我会以这种方式重构您的代码:
--total-executor-cores 9