I want to place a marker on Google Maps using Angular Google Maps my coordinates are from JSON file which when parses in Angular it's become a string.
Angular Google Maps does not support string for coordinates number. So It needs to be number.
marker.json
[
{
"id":"1",
"lat":"13.751814",
"lon":"100.501060"
},
{
"id":"2",
"lat":"13.738445",
"lon":"100.516805"
},
{
"id":"3",
"lat":"13.730209",
"lon":"100.779991"
}
]
maps.componenet.ts
import { Component, OnInit } from '@angular/core';
import {Http, Response} from '@angular/http';
@Component({
selector: 'app-maps',
templateUrl: './maps.component.html',
styleUrls: ['./maps.component.css']
})
export class MapsComponent implements OnInit {
private data;
constructor(private http:Http){
}
ngOnInit(){
this.getData();
}
getData(){
this.http.get('/localhost/marker.json')
.subscribe(res => this.data = res.json());
}
}
maps.component.html
<agm-map [latitude]="13.359665" [longitude]="101.035913" [zoom]="6">
<ng-container *ngFor="let list of data">
<agm-marker [latitude]="list.lat" [longitude]="list.lon"></agm-marker>
</ng-container>
</agm-map>
I have tried using parseFloat like this (Yes it's not working)
<agm-marker [latitude]="parseFloat(list.lat)" [longitude]="parseFloat(list.lon)"></agm-marker>
I'm thinking of using parseInt
inside maps.component.ts
file but I'm not sure where to put this.
May someone helps me or guide me how to solve this.And please let me know that am I providing sufficient information or not.
Thanks!
A cleaner and more performant way is to process data once and provide it in view in a way that doesn't need any other preparations:
getData(){
this.http.get('/localhost/marker.json')
.map(res => res.json())
.map((data: any[]) => data.map(
({ lon, lat, ...props }) => ({ lon: +lon, lat: +lat, ...props })
))
.subscribe(data => {
this.data = data;
});
}
If marker.json doesn't have other props except listed ones, ...props
can be replaced with known id
property.
Global functions like parseFloat
are not allowed in Angular templates (see the Angular documentation).
You can convert strings to numbers with the +
operator:
<agm-marker [latitude]="+list.lat" [longitude]="+list.lon"></agm-marker>
or define a method in your component:
convertCoordinate(str: string): number {
return parseFloat(str);
}
and call it in the template:
<agm-marker [latitude]="convertCoordinate(list.lat)" [longitude]="convertCoordinate(list.lon)"></agm-marker>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With