【问题标题】:How do I display an alert() off of a google maps 'marker' click?如何从谷歌地图的“标记”点击中显示警报()?
【发布时间】:2020-01-19 00:46:18
【问题描述】:

我有什么:enter image description here ...

google.maps.event.addListener(marker,'click',function() {

  this.map.setZoom(15);
  this.map.setCenter(marker.getPosition());
  console.log('hello world');
  this.presentAlert(); // ERROR core.js:9110 ERROR TypeError: 
  //this.presentAlert is not a function

});

...

我想要什么:enter image description here

我的代码扩展: ...

 public addMarker(lat: number, lng: number) {
    //let latLng = new google.maps.LatLng(lat, lng);
    let latLng = new google.maps.LatLng(21.576, -158.271); // hiking 
    // spot

    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: latLng
    });

    this.markers.push(marker); // catch 'em all

    google.maps.event.addListener(marker,'click',function() {

      this.map.setZoom(15);
      this.map.setCenter(marker.getPosition());
      console.log('hello world');
      this.presentAlert(); // ERROR core.js:9110 ERROR TypeError: 
      // this.presentAlert is not a function

    });

  }

presentAlert() {
        this.alertCtrl.create({
          header: 'Alert',
          subHeader: 'Subtitle',
          message: 'This is an alert message.',
          buttons: ['OK']
        }).then(alert=> {
          alert.present();
        });

      }

...

我尝试了其他一些方法,但对我来说,凭直觉,这是最有意义的。帮助?请和谢谢。

【问题讨论】:

    标签: javascript typescript google-maps ionic-framework google-maps-markers


    【解决方案1】:

    this 使用本地变量

    因为this 会根据其运行的上下文更改其值。

    public addMarker(lat: number, lng: number) {
      ...
    
      let that = this;
    
      google.maps.event.addListener(marker, 'click', function() {
        ...
    
        that.presentAlert();
      });
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-04
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多