Creating multiple markers with Angular Google Maps from an API
Creating multiple markers with Angular Google Maps from an API
I'm trying to create multiple markers in a Google Map with the AGM package. While I can create multiple markers hardcoding the latitude and longitude if I try to create them with data fetched from an API I can't make it work.
If I do a ngFor in a 'p' tag to show the latitude and longitude, it shows the data correctly but for some reason, it can't create the agm-markers. This is my code:
component.ts
gps_lats: Array<number>;
gps_longs: Array<number>;
constructor(private _api: ApiService) { }
ngOnInit() {
this._api.machinesLocation().subscribe(res => {
this.gps_lats = Object.values(res['data']).map(({ lat }) => lat);
this.gps_longs = Object.values(res['data']).map(({ long }) => long);
});
}
component.html
machinesLocation
jsoneditoronline.org/?id=45a9246fb7d04f0a86b0f7286a5adcd2
– DavidMM
Jul 3 at 9:04
Ok I will create a Stackblitz on demo
– Krishna Rathore
Jul 3 at 9:05
Hi @David I Have post a Solution with Stackblitz demo.
– Krishna Rathore
Jul 3 at 10:18
1 Answer
1
You can try with this solution
I have create a demo on Stackblitz
Component.ts
markers: Arary<any>=;
ngOnInit() {
this._api.machinesLocation().subscribe((res: any) => {
for(let data in res.data){
this.markers.push({
lat: parseInt(res.data[data].lat),
long: parseInt(res.data[data].long)
})
}
}
}
Component.html
<agm-marker
*ngFor="let m of markers;"
[latitude]="m.lat"
[longitude]="m.long">
</agm-marker>
Thanks a lot Krishna, this totally works. I had to fix a bit of the code as I'm using Angular 6 (just small things as fetching the data with res['data'] instead of res.data)', but now it works.
– DavidMM
Jul 3 at 10:34
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
hi @David plz provide json res of
machinesLocation
service– Krishna Rathore
Jul 3 at 8:39