1

I am new to Angular, and I have been trying to figure this out for hours. I can't get the lat and lng variables to return the number properly when I get them from JSON.

I am getting JSON from here: https://jsonplaceholder.typicode.com/users

Here is the component.html...

<div *ngIf="user$">

<ul>

  <li><strong>Lat:</strong> {{ lat }}</li>
  <li><strong>Lng:</strong> {{ lng }}</li>

</ul>

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

</div>

It works as it should in the list and map elements when I set the values in the variables this way.

Working component.ts

export class DetailsComponent implements OnInit {

  user$: any;

  constructor(private data: DataService, private route: ActivatedRoute) { 
    this.route.params.subscribe( params => this.user$ = params.id)
  }

  ngOnInit() :void {
    this.data.getUser(this.user$).subscribe(
      data => {
        this.user$ = data 
        console.log(this.lat, this.lng);

      } 
    )

  }
        lat: number = -37.3159;
        lng: number = 81.1496;

}

But as soon as I try to get values from JSON the variables return as the string, and the map and the marker don't work but the list element does.

Not working component.ts

export class DetailsComponent implements OnInit {

  user$: any;
  lat: number;
  lng: number;

  constructor(private data: DataService, private route: ActivatedRoute) { 
    this.route.params.subscribe( params => this.user$ = params.id)
  }

  ngOnInit() :void{
    this.data.getUser(this.user$).subscribe(
      data => {
        this.user$ = data 
        this.lat = this.user$.address.geo.lat;
        this.lng = this.user$.address.geo.lng;
        console.log(this.lat, this.lng);
      } 
    )

  }

}

When I hover over the lat and lng variables in the Visual Studio Code either way, it looks identical and it says (property) DetailsComponent.lng : number or (property) DetailsComponent.lng : number.

1 Answer 1

3

Because agm expects an integer value and you provide a string. I think the best way to convert it into number value (in case if your number format uses dot . (not comma ,), use a + sign:

this.lat = +this.user$.address.geo.lat;
this.lng = +this.user$.address.geo.lng;
Sign up to request clarification or add additional context in comments.

2 Comments

I also got it to work this way. I placed an function in the ts file. ConvertString(value){ return parseFloat(value) } and changed the html to [latitude]="ConvertString(lat)" and [longitude]="ConvertString(lng)".
p.s. I wouldn't write a dollar sign here this.user$ = data. Thats a convention for streams, like Observable. It might confuse other programmers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.