0

If I hardcode the data, then all markers will show up nicely. If I comment the line this.markers.push(newMarker); and replace it with the next, I get an ERROR TypeError: Cannot read property 'push' of undefine

If I use the this.markers = [newMarkers] only one the last json element shows up as marker.

How can I show all the markers at one, is it a problem with async ?

ngOnInit() {

this._mapService.getMarkers().subscribe(data => {

    data.map(a => {
      const lat = a.lat;
      const lng = a.lng;
      const name = a.name;

      const newMarker = marker(
        [lat, lng], {
          icon: icon({
            iconSize: [25, 25],
            iconAnchor: [13, 41],
            iconUrl: 'assets/yellow.png',
          })
        }
      );
      newMarker.bindPopup('<p>' + name + '</p>', {autoPan: true});

      // this.markers.push(newMarker);

      this.markers = [newMarker];
 });

Service

@Injectable({
  providedIn: 'root'
})
export class MapserviceService {

  private _markers = '../../assets/markers/markers.json';

  constructor(private http: HttpClient) {}

  getMarkers(): Observable<any> {
   return this.http.get<any>(this._markers);
  }

JSON data

[{
    "name": "Canada",
    "lat": 56.130366,
    "lng": -106.346771
  },
...
  {
    "name": "Anguilla",
    "lat": 18.220554,
    "lng": -63.068615
  }
]

hardcoded data that works

  function createIcon2() {
    return icon({
      iconSize: [25, 25],
      iconAnchor: [13, 41],
      iconUrl: 'assets/yellow.png',
    });
  }

  this.markers =
    [
      marker([35, -76], { icon: createIcon2() }),
      marker([36, -81], { icon: createIcon2() }),
      marker([37, -88], { icon: createIcon2() }),
      marker([38, -99], { icon: createIcon2() }),
      marker([39, -111], { icon: createIcon2() })
    ];

    console.log('working', this.markers); 
brohymn
  • 460
  • 5
  • 22
  • How do you initialize `this.markers`? – ghybs Jul 16 '18 at 06:12
  • I guess I didnt, I was just following the ngx-leaflet example https://github.com/Asymmetrik/ngx-leaflet/blob/master/src/demo/app/leaflet/performance/performance-demo.component.ts. I've used changeondetectionstrategy but didnt work – brohymn Jul 16 '18 at 06:19
  • or maybe I did?.... public markers: Marker[]; – brohymn Jul 16 '18 at 06:35

1 Answers1

2

public markers: Marker[]; declares your markers member but does not initialize / assign it anything.

The : Markers[] part is for TypeScript type declaration, but does not initialize.

public markers: Marker[] = [] would initialize it to an array, on which you can use the push method.

ghybs
  • 47,565
  • 6
  • 74
  • 99