1
Angular 2で実行しているGoogleマップの実装を試してみました。Angularサービスが提供するマーカーの束を表示したいと思います。Googleマップとangle2のスコープの問題?
「例外:TypeError:this.markersは[null]で定義されていません」これを手伝っていただければ幸いです。
おかげ フレッド
は、これはこれまでのところ、私のコンポーネントです:
ngOnInit(){
this.getDecisionsGeo();
this.initializeMap();
}
のでinitializeMap
方法は、結果の前に呼び出されます。
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);
});
}
}
}
ティエリー、あなたの提案がマップを起動して実行しました!終了:)。あなたの提案がどのように機能するかまだ完全にはっきりしていません。 NgOnitのメソッドは同期的に呼び出されますか?私は、彼らが順番に、トップダウンで実行すると思った。これを明確にしてくれてありがとう。 – Fred30
よろしくお願いします!実際、最初の呼び出しは非同期です。これはマーカーのリストが(initializeMapが呼び出された後に)後で受け取られることを意味します。データが受信されるのを待つ必要があります( 'subscribe'コールバック内)... –