标记点击事件未触发

时间:2018-11-09 14:43:54

标签: google-maps-api-3 google-maps-markers

我已经制作了一些已经在生产中的代码,但是我遇到了一些标记没有附加click事件的问题。

为使此工作正常进行,我剥离了代码,并在当前代码的结构内实现了本页中显示的基本示例https://developers.google.com/maps/documentation/javascript/examples/event-simple

但是,这不起作用,设置了标记,但未附加click事件。

在地图上添加点击事件即可。

有人对导致此问题的原因有什么建议吗?

init() {
    this.loadScript(`https://maps.googleapis.com/maps/api/js?client=${this.apiClient}`);
}

loadScript(url) {
    const script = document.createElement('script');

    script.type = 'text/javascript';

    script.src = url;
    document.getElementsByTagName('body')[0].appendChild(script);

    setTimeout(() => {
        this.initMap();
    }, 500);
}

initMap() {
    const myLatlng = {lat: -25.363, lng: 131.044};

    const map = new google.maps.Map(this.mapElement, {
        zoom: 4,
        center: myLatlng
    });

    const marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: 'Click to zoom'
    });

    map.addListener('center_changed', function() {
        // 3 seconds after the center of the map has changed, pan back to the
        // marker.
        window.setTimeout(function() {
            map.panTo(marker.getPosition());
        }, 3000);
    });

    marker.addListener('click', function markerClick() {
        map.setZoom(8);
        map.setCenter(marker.getPosition());
    });
}

1 个答案:

答案 0 :(得分:0)

我做了一些修改并开始工作

const marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: 'Click to zoom',
            icon: 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png'
        });

        map.addListener('center_changed', function () {
            // 3 seconds after the center of the map has changed, pan back to the
            // marker.
            window.setTimeout(function () {
                map.panTo(marker.getPosition());
            }, 3000);
        });

        marker.addListener('click', function () {
            map.setZoom(8);
            map.setCenter(marker.getPosition());
        });
        marker.setMap(map);

相关问题