【问题标题】:Pass function result into property将函数结果传递给属性
【发布时间】:2025-12-04 11:40:01
【问题描述】:

我正在使用 Google Maps SDK 构建一个 Ionic 2 应用程序。

我希望用户能够在地图上添加标记。

我通过按钮单击添加标记的代码如下所示:

addMarker(){

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

    let content = "<h4>Information!</h4>";          

    this.addInfoWindow(marker, content);

}

position: this.map.getCenter() 使 Pin 始终添加在地图的中心。

以下函数应返回地图上点击地点的纬度/经度:

addNewPlace(){
  let newPlace = new google.maps.event.addListener(this.map, 'click', (event) => latLng);
}

我希望将上面的结果 (latLng) 插入到 addMarker 函数中:

addMarker(){

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

    let content = "<h4>Information!</h4>";          

    this.addInfoWindow(marker, content);

}

我该怎么做? 现在浏览器只是忽略了我的 addNewPlace 函数(没有任何反应,控制台中没有错误)。

【问题讨论】:

    标签: angular google-maps google-maps-api-3 ionic2


    【解决方案1】:

    您可以在创建地图的初始化函数中为地图添加点击监听器。无需创建 addNewPlace() 函数。另请注意,google.maps.event.addListener() 没有构造函数。不需要 new 运算符。

    https://developers.google.com/maps/documentation/javascript/reference#event

    点击事件的回调函数返回一个 MouseEvent 对象

    https://developers.google.com/maps/documentation/javascript/reference#MouseEvent

    所以你可以创建一个函数

    addMarker(newPlace) {
    
        let marker = new google.maps.Marker({
            map: this.map,
            animation: google.maps.Animation.DROP,
            position: newPlace
        });
    
        let content = "<h4>Information!</h4>";          
    
        this.addInfoWindow(marker, content);
    }
    

    在地图创建后的初始化函数中添加

    google.maps.event.addListener(this.map, 'click', (event) => {
        addMarker(event.latLng);
    });
    

    【讨论】: