如何为列表中的每个标记创建单独的监听器

一旦你这样做:


const currencies = [euro, yen];

没有从back 到或从back 到 的链接。获取和变量的值并将这些值放入数组中。currencies[0]eurocurrencies[1]yen[euro, yen]euroyen


尝试对您所拥有的进行最小的更改,您可以使用对象而不是数组:


for (let [currencyName, currencyValue] of Object.entries({euro, yen})) {    

    const pair = await fetchPairData(currencyValue, dollar);

    const route = new Route([pair], dollar);

    console.log(currencyName, currencyValue + route.midPrice.toSignificant(6));

}我有一个坐标列表,通过它在地图上设置标记。标记仅以小于 12 的放大倍数出现在地图上。我想使当我单击标记时执行某些功能,并且仅执行一次。


现在事情是这样的:


for (let i = 0; i < locationsCoordinates.length; i++) {

    const bridge = locationsCoordinates[i];

    markers.push( new google.maps.Marker({

        position: bridge[1],

        title: bridge[0],

        map,

        icon: 'img/bridges.png',

        clickable: true,

    }));

}


google.maps.event.addListener(map, 'zoom_changed', function() {

    let zoom = map.getZoom();

    if (zoom < 12) {

        for (let i = 0; i < markers.length; i++) {

            markers[i].setVisible(false);

            markers[i].addListener("click", function (event) {

                test +=1;

            });

            }

        }

     else {

        for (let i = 0; i < markers.length; i++) {

            markers[i].setVisible(true);

        }

    }

})

问题是,对于这样的代码,当您单击任何标记时,该函数会运行多次。


郎朗坤
浏览 137回答 2
2回答

慕桂英3389331

您需要使用addListenerOnce并稍微重构您的代码。像这样的东西var locationsCoordinates = [{lat: 12.84, lng: 122.89}, {lat: 12.80, lng: 122.93}, {lat: 12.74, lng: 122.85}];var markers = [];for (let i = 0; i < locationsCoordinates.length; i++) {    var marker = new google.maps.Marker({        position: locationsCoordinates[i],        map    });        google.maps.event.addListenerOnce(marker, "click", () => {        console.log("marker", i, "clicked");    });        markers.push(marker);}google.maps.event.addListener(map, 'zoom_changed', function() {    let zoom = map.getZoom();    if (zoom < 12) {        for (let i = 0; i < markers.length; i++) {            markers[i].setVisible(false);        }    } else {        for (let i = 0; i < markers.length; i++) {            markers[i].setVisible(true);        }    }})

慕容森

创建标记时,将侦听器添加到标记,如相关示例中所示。不在zoom_changed地图上的事件监听器中。不确定为什么要在标记隐藏时添加侦听器(.setVisible(false)大小写),而不是在显示标记时添加侦听器,但如果在创建标记时将侦听器添加到标记,则不需要执行任何特殊操作。相关问题使用函数闭包将标记与其InfoWindow内容相关联(或者单击标记时您想要执行的任何操作),下面的代码使用关键字let,这是该问题的现代解决方案,但函数更接近可以用作好吧,特别是如果您需要支持旧版浏览器。&nbsp; for (let i = 0; i < locationsCoordinates.length; i++) {&nbsp; &nbsp; const bridge = locationsCoordinates[i];&nbsp; &nbsp; let marker = new google.maps.Marker({&nbsp; &nbsp; &nbsp; position: bridge[1],&nbsp; &nbsp; &nbsp; title: bridge[0],&nbsp; &nbsp; &nbsp; map,&nbsp; &nbsp; &nbsp; icon: 'img/bridges.png',&nbsp; &nbsp; &nbsp; clickable: true,&nbsp; &nbsp; });&nbsp; &nbsp; markers.push(marker);&nbsp; &nbsp; google.maps.event.addListener(marker, 'click', function(evt) {&nbsp; &nbsp; &nbsp; infowindow.setContent(locationsCoordinates[i][0]);&nbsp; &nbsp; &nbsp; infowindow.open(map, marker);&nbsp; &nbsp; &nbsp; test += 1;&nbsp; &nbsp; });&nbsp; }&nbsp; google.maps.event.addListener(map, 'zoom_changed', function() {&nbsp; &nbsp; let zoom = map.getZoom();&nbsp; &nbsp; if (zoom < 12) {&nbsp; &nbsp; &nbsp; for (let i = 0; i < markers.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; markers[i].setVisible(false);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; for (let i = 0; i < markers.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; markers[i].setVisible(true);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; })概念证明小提琴代码片段:// The following example creates markers to indicate beaches near// Sydney, NSW, Australia.&nbsp;let markers = [];let test = 0;function initMap() {&nbsp; const map = new google.maps.Map(document.getElementById("map"), {&nbsp; &nbsp; zoom: 10,&nbsp; &nbsp; center: {&nbsp; &nbsp; &nbsp; lat: -33.9,&nbsp; &nbsp; &nbsp; lng: 151.2&nbsp; &nbsp; },&nbsp; });&nbsp; let infowindow = new google.maps.InfoWindow();&nbsp; // Adds markers to the map.&nbsp; for (let i = 0; i < locationsCoordinates.length; i++) {&nbsp; &nbsp; const bridge = locationsCoordinates[i];&nbsp; &nbsp; let marker = new google.maps.Marker({&nbsp; &nbsp; &nbsp; position: bridge[1],&nbsp; &nbsp; &nbsp; title: bridge[0],&nbsp; &nbsp; &nbsp; map,&nbsp; &nbsp; &nbsp; clickable: true,&nbsp; &nbsp; });&nbsp; &nbsp; markers.push(marker);&nbsp; &nbsp; google.maps.event.addListener(marker, 'click', function(evt) {&nbsp; &nbsp; &nbsp; infowindow.setContent(locationsCoordinates[i][0]);&nbsp; &nbsp; &nbsp; infowindow.open(map, marker);&nbsp; &nbsp; &nbsp; test += 1;&nbsp; &nbsp; &nbsp; console.log("open infowindow:" + this.getTitle() + " test=" + test);&nbsp; &nbsp; });&nbsp; }&nbsp; google.maps.event.addListener(map, 'zoom_changed', function() {&nbsp; &nbsp; let zoom = map.getZoom();&nbsp; &nbsp; if (zoom < 12) {&nbsp; &nbsp; &nbsp; infowindow.close();&nbsp; &nbsp; &nbsp; for (let i = 0; i < markers.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; markers[i].setVisible(false);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; for (let i = 0; i < markers.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; markers[i].setVisible(true);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; })}// Data for the markers consisting of a name and a LatLng.const locationsCoordinates = [&nbsp; ["Bondi Beach", {&nbsp; &nbsp; lat: -33.890542,&nbsp; &nbsp; lng: 151.274856&nbsp; }],&nbsp; ["Coogee Beach", {&nbsp; &nbsp; lat: -33.923036,&nbsp; &nbsp; lng: 151.259052&nbsp; }],&nbsp; ["Cronulla Beach", {&nbsp; &nbsp; lat: -34.028249,&nbsp; &nbsp; lng: 151.157507&nbsp; }],&nbsp; ["Manly Beach", {&nbsp; &nbsp; lat: -33.80010128657071,&nbsp; &nbsp; lng: 151.28747820854187&nbsp; }],&nbsp; ["Maroubra Beach", {&nbsp; &nbsp; lat: -33.950198,&nbsp; &nbsp; lng: 151.259302&nbsp; }],];/* Always set the map height explicitly to define the size of the div&nbsp; &nbsp; &nbsp; &nbsp;* element that contains the map. */#map {&nbsp; height: 100%;}/* Optional: Makes the sample page fill the window. */html,body {&nbsp; height: 100%;&nbsp; margin: 0;&nbsp; padding: 0;}<!DOCTYPE html><html><head>&nbsp; <title>Complex Marker Icons</title>&nbsp; <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>&nbsp; <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>&nbsp; <!-- jsFiddle will insert css and js --></head><body>&nbsp; <div id="map"></div></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript