mibrl12
mibrl12

Reputation: 484

angular2 - How to add markers to a map after initialization in ngOnInit?

I am getting started with Angular and building an example app with GoogleMaps.

import { Component, Input, OnInit, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormControl } from '@angular/forms';
import Appcomponent = require("../app.component");
import Accident = Appcomponent.Accident;
declare var google: any;
declare let map: any

@Component({
  selector: 'app-map',
  templateUrl: 'map.component.html',
  styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {

  private http: HttpClient;
  private baseUrl: string;

  private tags: string[];
  private accidents: Accident[];
  private accidentsMarkers: any[] = [];
  private markers: any[] = [];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.http = http;
    this.baseUrl = baseUrl;
  }

  ngOnInit() {
    var mapProp = {
      center: new google.maps.LatLng(51.508742, -0.120850),
      zoom: 5,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
  }


  public loadAccidents(): void {
    this.http.get<Accident[]>(this.baseUrl + 'api/accidents').subscribe(result => {
      this.accidents = result;

      this.accidents.forEach(function (accident) {
        var marker = new google.maps.Marker({
          position: new google.maps.LatLng(accident.location.coordinates.lat,
            accident.location.coordinates.lon),
          map: this.map,
          title: ""
        });
        this.markers.push(marker);
      });
    }, error => console.error(error));    
  }
}

So basically map is initialized in ngOnInit and when I try to access map in loadAccidents I get: ERROR TypeError: Cannot read property 'markers' of undefined.

As I understood constructor is called first, then ngOnInit. Therefore, I assume, that map has been defined.

Is there any other better way to integrate google map into an Angular app? Or what am I doing wrong?

Upvotes: 1

Views: 987

Answers (1)

zcharles
zcharles

Reputation: 190

Change the way you iterate on this.accidents for an Arrow Function .i.e. this.accidents.forEach(accident => {... Your code here... });

Upvotes: 1

Related Questions