Search code examples
google-mapsbindingangular-google-maps

Agm google maps - how to bind latitude and longitude to HTML


I am facing a issue in binding the latitude and longitude parameters that I have got from AJAX response. If i hardcode the latitude and longitude in HTML, it works fine. But when i pass the data from response, it just doesnt work.

  <agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
                <agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
              </agm-map>

     ngOnInit() {
        this.getTransactionView(this.selectedTransaction);
      }

    getTransactionView(selectedTransaction): void {

        const resultArray = {
          'latitude': '51.525244',
          'longtitude': '-0.141186'
        };
        this.transactionResult = resultArray;
        this.latitude = this.transactionResult.latitude;
        this.longitude = this.transactionResult.longtitude;
       console.log(this.latitude);
      console.log(this.longitude);
// console.log prints the values, but after binding to HTML , it doesnt display the marker
      }
}

Solution

  • Most likely it occurs since the provided values of string type.

    AgmMarker expects latitude and longitude values of number type, for example:

    map.component.html:

    <agm-map [latitude]="lat" [longitude]="lng">
        <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
    </agm-map>
    

    map.component.ts:

    export class MapComponent implements OnInit {
      lat: number;
      lng: number;
      constructor(private http: HttpClient) {}
    
      ngOnInit() {
        this.initData();
      }
    
    
      initData(): void {
        this.http.get<{}>('./assets/data.json')
        .subscribe(result => {
          console.log(result);
          this.lat = parseFloat(result['lat']);
          this.lng = parseFloat(result['lng']);
        });
      }
    
    }
    

    Here is a demo for your reference