this.map.getCenter() Cannot read property

I have created a provider for google map Refrence: Location Select Page with Google Maps and Ionic | Josh Morony

Inside google.maps.event.addListener when trying to call alert(this.map.getCenter());

I am getting error:

main.js:564
TypeError: Cannot read property ‘getCenter’ of undefined
main.js:569
at Qg. (file:///android_asset/www/build/main.js:569:36)
at trigger (http://maps.google.com/maps/api/js?key=MY_API_KEY&callback=mapInit&libraries=places:123:449)
at http://maps.google.com/maps-api-v3/api/js/31/7/common.js:8:135
at _.Vo.H (http://maps.google.com/maps-api-v3/api/js/31/7/common.js:200:2336)
at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:15660)

Versions:
@angular/common”: “5.0.0”,
@ionic-native/core”: “4.3.2”,

Code:

import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Connectivity } from './wifi-connectivity-service';
import { Geolocation } from '@ionic-native/geolocation';

declare var window: any;

@Injectable()
export class GoogleMapsProvider {

  mapElement: any;
  pleaseConnect: any;
  map: any;
  mapInitialised: boolean = false;
  mapLoaded: any;
  mapLoadedObserver: any;
  currentMarker: any;
  apiKey: string = "MY_API_KEY";
  marker: any = null;

  constructor(
    public connectivityService: Connectivity,
    public geolocation: Geolocation
  ) {
  }

  init(mapElement: any, pleaseConnect: any): Promise<any> {

    this.mapElement = mapElement;
    this.pleaseConnect = pleaseConnect;
    return this.loadGoogleMaps();

  }

  loadGoogleMaps(): Promise<any> {
    return new Promise((resolve) => {
      if (typeof google == "undefined" || typeof google.maps == "undefined") {

        this.disableMap();
        if (this.connectivityService.isOnline()) {

          window['mapInit'] = () => {
            this.initMap().then(() => {
              resolve(true);
            });
            this.enableMap();
          }

          let script = document.createElement("script");
          script.id = "googleMaps";

          if (this.apiKey) {
            script.src = 'http://maps.google.com/maps/api/js?key=' + this.apiKey + '&callback=mapInit&libraries=places';
          } else {
            script.src = 'http://maps.google.com/maps/api/js?callback=mapInit';
          }

          document.body.appendChild(script);

        }
      } else {

        if (this.connectivityService.isOnline()) {
          this.initMap();
          this.enableMap();
        }
        else {
          this.disableMap();
        }
        resolve(true);
      }

      this.addConnectivityListeners();

    });

  }

  initMap(): Promise<any> {

    this.mapInitialised = true;

    return new Promise((resolve) => {

      this.geolocation.getCurrentPosition().then((position) => {

        let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        let mapOptions = {
          center: latLng,
          zoom: 15,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          disableDefaultUI: true
        }

        this.map = new google.maps.Map(this.mapElement, mapOptions);
        //HERE I AM GETTING DATA:
        console.log("getCenter(): " + this.map.getCenter());
        google.maps.event.addListener(this.map, 'idle', function () {
          //HERE I AM GETTING ABOVE MENTIONED ERROR:
          alert(this.map.getCenter());
        });
        resolve(true);
      }, (err) => {
        console.log(err);
      });

    });

  }

  disableMap(): void {

    if (this.pleaseConnect) {
      this.pleaseConnect.style.display = "block";
    }

  }

  enableMap(): void {

    if (this.pleaseConnect) {
      this.pleaseConnect.style.display = "none";
    }

  }

  addConnectivityListeners(): void {

    this.connectivityService.watchOnline().subscribe(() => {

      setTimeout(() => {

        if (typeof google == "undefined" || typeof google.maps == "undefined") {
          this.loadGoogleMaps();
        }
        else {
          if (!this.mapInitialised) {
            this.initMap();
          }

          this.enableMap();
        }

      }, 2000);

    });

    this.connectivityService.watchOffline().subscribe(() => {

      this.disableMap();

    });

  }

}

Check on this Google Maps.

Not getting any help already seen this before.

It must be that bounds is undefined, so map is not (yet) valid. Have you checked map when it’s passed to calculateRadiusInMiles()? Have you checked bounds? Has the map already loaded?

Google Maps Api v3 - getBounds is undefined

Edit to spoon-feed:

It looks like there’s an event in v3 for exactly this:

`google.maps.event.addListener(map, 'bounds_changed', function() {
     alert(map.getBounds());
});
or

`google.maps.event.addListener(map, 'idle', function() {
     alert(map.getBounds());
});

[ts] Cannot find name ‘map’. Did you mean ‘Map’?

Map is already loaded after loading when user move map and stop some where I am trying to get the coordinates of that location.

also tried:

google.maps.event.addListener(new google.maps.Map(this.mapElement, mapOptions), 'idle', function () {
          alert(this.map.getBounds());
});

this is also not working from me getting same error as mentioned before.

I thik this Link help to you.please check
Thank you.

SOLUTION:
use arrow function and when not , Coz of the function(){} you were not getting the scope of parent inside it , if you wan that you should use () => {}

google.maps.event.addListener(this.map, 'center_changed', () => {
    alert(this.map.getCenter());
});
1 Like