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