Can't display marker from http.get

map: any;

  @ViewChild('map', {read: ElementRef, static: false}) mapRef: ElementRef;
  data: any;
  infoWindows: any = [];
  markers: any = {};


  constructor(private http: HttpClient) {}

  get_location(){
    this.http.get('http://gsmgpsppm.000webhostapp.com/fetch_data.php')
    .subscribe(data =>{
      console.log("received: " + JSON.stringify(data[0][0]));
      this.markers = JSON.stringify(data[0][0]);
    });
  }

  ionViewDidEnter() {
    this.showMap();
  }

  addMarkersToMap() {
    this.get_location();
    let position = new google.maps.LatLng( this.markers["latitude"] ,  this.markers["longitude"] );
    let mapMarker = new google.maps.Marker({
      position: position,
      latitude: this.markers["latitude"],
      longitude: this.markers["longitude"]
    });

Given the above code, in function LatLng I can’t display markers data, received from an http.get as:

Is there anything wrong with the syntax??

Lots of things.

  • functions should be camelCase, not snake_case, so get_location should be getLocation
  • getLocation shouldn’t be in a page, it should be in a service
  • similarly, you should not be injecting HttpClient into a page - do that in the service
  • functions named getSomething should return the “something” directly, as opposed to modifying external state

If you rearchitect things thusly, you’ll design away your race condition:

class LocationService {
  getLocation(): Observable<google.maps.LatLng> {
    return this.http.get(url).pipe(
      map(rsp => rsp[0][0]),
      map(pt => new google.maps.LatLng(pt)));
  }
}

class MapPage {
  constructor(private locations: LocationService) {}

  addMarkersToMap(): void {
    this.locations.getLocation().subscribe(latlng => {
      // do your marker stuff here
    }
}