首页 > 解决方案 > 无法从 Ionic 3 中的 Google Map Listener 函数中访问全局函数

问题描述

我有一个“附近”屏幕,其中列出了位置并按与用户位置的最近距离(从地理位置获得)对它们进行排序。我还创建了一个使用地图标记来显示位置的地图(Google JavaScript API)。这是使用离子 3。

我无法弄清楚如何从 Google 的 InfoWindow 访问“goShopPage()”函数。我可以打开信息窗口,并成功单击信息窗口以执行 console.log 功能,或该块中的任何其他功能。

但是,当我尝试使用 this.goShopPage 访问 goShopPage() 函数时,出现以下错误:

“未捕获的 TypeError:this.goShopPage 不是函数”

我已经尝试将它包装在一个虚拟变量中,以及其他一些没有运气的方法。

我已经为此工作了一整天。对此的任何帮助将不胜感激!

  export class GmapComponent implements OnInit{

  @ViewChild ('map') mapElement;

  map: any;
  stores: any;
  infoWindows: any;

  constructor( public geolocation: Geolocation, private alertCtrl: AlertController, public navCtrl: NavController, public restProvider: RestProvider) {
    this.infoWindows = [];
  }

  ngOnInit() { 
    this.loadMap();    
  }

  goShopPage() {
    console.log("Info Window Button Clicked");
  }

  //Loads map on the screen
  loadMap() {

    let i: any;
    let locations: any = [];

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

      let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      console.log("Coordinates", latLng);
      const mapOptions: google.maps.MapOptions = {
      center: latLng, 
      zoom: 17, 

      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);


      //Load data from REST API
      this.restProvider.getStores().then(data => {
              locations = data;

              for (i = 0; i < locations.length; i++) { 
                const marker: google.maps.Marker = new google.maps.Marker({
                  position: new google.maps.LatLng(locations[i].lat, locations[i].longi),
                  map: this.map,
                });
                google.maps.event.addListener(marker, 'click', (function(marker, i) {

                  let windowContent = ` 
                  <div id="content">
                    <h6 id="firstHeading" class="firstHeading">` + locations[i].name + `</h6>
                    <p id="tap">Open Page</p>
                  </div>`;

                  let infoWindow = new google.maps.InfoWindow({
                    content: windowContent
                  });

                  google.maps.event.addListenerOnce(infoWindow, 'domready', () => {
                    document.getElementById('tap').addEventListener('click', () => {

                      console.log("InfoWindow Clicked");
                      this.goShopPage();

                    });
                  });

                  return function() {
                    infoWindow.open(this.map, marker);
                  }
                })(marker, i));
              }
            });
  }

标签: javascriptgoogle-mapsnestedionic3infowindow

解决方案


推荐阅读