简体   繁体   中英

Scope issue with google maps and angular2?

Trying to get Google Maps implementation running in Angular 2. I want to display a bunch of markers, served by an Angular service.

I get an "EXCEPTION: TypeError: this.markers is undefined in [null]" It would be great if you can help me with this!

Thanks Fred

This is my component so far:

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);

            });
        } 

    }

}

The problem is that you load markers asynchronously:

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

So the initializeMap method is called before the result of the HTTP request is received.

I would refactor your code this way:

ngOnInit(){
  this.getDecisionsGeo();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM