如何向多个标记添加相同的事件侦听器,然后区分 Google Maps API v3 中侦听器中的标记?

发布于 2024-12-08 22:34:24 字数 616 浏览 2 评论 0原文

我的 Javascript 中的许多标记都有相同的事件侦听器。如何区分此侦听器中的不同标记?我想在单击特定标记时在其他地方显示另一个标记。每个标记都有另一个标记,我在单击它时显示它。

事件侦听器代码:

google.maps.event.addListener(marker, 'click', function() {
//code goes here

});

更详细:

我有两个数组 markers1markers2,每个数组都有 10 个标记。我在地图上显示了 markers1 中的 10。单击 markers1[0] 标记时,我想在地图上显示 markers2[0] 标记。我如何知道在事件监听器中我点击了 markers1[0],现在我知道我可以使用 THIS 来识别 markers1[0] 但我如何在侦听器中知道它是数组 markers1 中位置 0 处的标记,以便我也可以在数组 markers2 中位置 0 处显示标记>?

I have the same event listener for many markers in my Javascript. How do I differentiate between different markers in this listener? I want to display another marker elsewhere on clicking of a particular marker. Every marker has another marker which I display on clicking on it.

The event listener code:

google.maps.event.addListener(marker, 'click', function() {
//code goes here

});

More detail:

I have two arrays markers1 and markers2 each having 10 markers. I display the 10 from markers1 on my map. On clicking markers1[0] marker I want to display the markers2[0] marker on the map. How do I know in the event listener that I have clicked on markers1[0], now I know that I can use the THIS for identifying markers1[0] but how do I know in the listener that it was the marker at the position 0 in array markers1 so that I could also display marker at position 0 in array markers2?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

别想她 2024-12-15 22:34:24

您可以轻松地将索引(或任何其他信息)添加到每个标记:

for( var i = 0; i < arrDestinations; i += 1 ) {
    var marker = new google.maps.Marker({
        title: arrDestinations[i].title,
        position: new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lon),
        map: map,
        myIndex: i    // ADDED FIELD: Each marker contains its index
    )};
    bindInfoWindow(marker,map,infowindow,"<p>arrDestinations[i].description + "</p>");
}

然后在您的事件处理程序中,您可以执行以下操作:

google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(html);
    infowindow.open(map, marker);
    setVisibility(marker);  // ADDED
});

setVisibility 函数将类似于上面 150PoundsOfDonamite 建议的函数,只是您知道该标记的索引你想让可见:

function setVisible(marker) {
    for(var i=0; i<markers1.length; i++) {
        if(i==marker.myIndex) {
            markers2[i].setVisible(true);
        } else {
            markers2[i].setVisible(false);
        }
    }
}

You can easily add the index (or any other information) to each Marker:

for( var i = 0; i < arrDestinations; i += 1 ) {
    var marker = new google.maps.Marker({
        title: arrDestinations[i].title,
        position: new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lon),
        map: map,
        myIndex: i    // ADDED FIELD: Each marker contains its index
    )};
    bindInfoWindow(marker,map,infowindow,"<p>arrDestinations[i].description + "</p>");
}

Then in your event handler you can do this:

google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(html);
    infowindow.open(map, marker);
    setVisibility(marker);  // ADDED
});

The setVisibility function would be similar to the one suggested by 150PoundsOfDonamite above, except that you know the index of the marker that you want to make visible:

function setVisible(marker) {
    for(var i=0; i<markers1.length; i++) {
        if(i==marker.myIndex) {
            markers2[i].setVisible(true);
        } else {
            markers2[i].setVisible(false);
        }
    }
}
心奴独伤 2024-12-15 22:34:24

实际上,每个标记都没有相同的侦听器,或者至少没有相同的处理函数;你只有相同的代码。

在 JavaScript 中,函数是一等对象,并且在迄今为止发布的所有答案中,正在为每个标记创建一个单独的函数。这是浪费内存。

这就是我认为你想要的:

var myMarkerClickHandler = function() {
    // use the keyword 'this' to access the marker that got clicked
    console.debug('Marker for ' + this.arrDestination.title + ' got clicked!');
    console.debug('Its position is ' + this.position);
}

for (i = 0; i < arrDestinations.length; i++) {
    // create a marker
    var marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lon),
        // as @john-black says, you can add whatever properties you like to the marker
        arrDestination: arrDestinations[i]
    });

    // add *the* event handler to this marker
    google.maps.event.addListener(marker, 'click', myMarkerClickHandler);
}

You don't actually have the same listener for each marker, or at least not the same handler function; you just have the same code.

In JavaScript, functions are first-class objects, and in all the answers posted so far, a separate function is being created for each marker. This is a waste of memory.

Here's what I think you want:

var myMarkerClickHandler = function() {
    // use the keyword 'this' to access the marker that got clicked
    console.debug('Marker for ' + this.arrDestination.title + ' got clicked!');
    console.debug('Its position is ' + this.position);
}

for (i = 0; i < arrDestinations.length; i++) {
    // create a marker
    var marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lon),
        // as @john-black says, you can add whatever properties you like to the marker
        arrDestination: arrDestinations[i]
    });

    // add *the* event handler to this marker
    google.maps.event.addListener(marker, 'click', myMarkerClickHandler);
}
绻影浮沉 2024-12-15 22:34:24

您可以做的是使用一个外部函数来处理标记/信息窗口的添加(请参阅 150PoundsOfDonamite 的评论)。巧合的是,我今天写了一篇博文,展示了如何来做到这一点。

<script type="text/javascript">
function initialize() {
    var i;
    var arrDestinations = [
        {
            lat: 50.815155,
            lon: -0.137072,
            title: "Brighton Pier",
            description: "Brighton Palace Pier dates to 1899"
        },
        {
            lat: 50.822638,
            lon: -0.137361,
            title: "Brighton Pavilion",
            description: "The Pavilion was built for the Prince of Wales in 1787"
        },
        {
            lat: 50.821226,
            lon: -0.139372,
            title: "English's",
            description: "English's Seafood Restaurant and Oyster Bar"
        }
    ];

    var myOptions = {
        zoom: 15,
        center: new google.maps.LatLng(50.820645,-0.137376),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var infowindow =  new google.maps.InfoWindow({
        content: ''
    });

    // loop over our array
    for (i = 0; i < arrDestinations.length; i++) {
        // create a marker
        var marker = new google.maps.Marker({
            title: arrDestinations[i].title,
            position: new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lon),
            map: map
        });

        // add an event listener for this marker
        bindInfoWindow(marker, map, infowindow, "<p>" + arrDestinations[i].description + "</p>");
    }
}

function bindInfoWindow(marker, map, infowindow, html) {
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(html);
        infowindow.open(map, marker);
    });
} 

google.maps.event.addDomListener(window, 'load', initialize);
</script>

What you can do is have an external function which handles the adding of markers/infowindows (see 150PoundsOfDonamite's comment). Coincidentally I wrote a blog post today that shows how to do this.

<script type="text/javascript">
function initialize() {
    var i;
    var arrDestinations = [
        {
            lat: 50.815155,
            lon: -0.137072,
            title: "Brighton Pier",
            description: "Brighton Palace Pier dates to 1899"
        },
        {
            lat: 50.822638,
            lon: -0.137361,
            title: "Brighton Pavilion",
            description: "The Pavilion was built for the Prince of Wales in 1787"
        },
        {
            lat: 50.821226,
            lon: -0.139372,
            title: "English's",
            description: "English's Seafood Restaurant and Oyster Bar"
        }
    ];

    var myOptions = {
        zoom: 15,
        center: new google.maps.LatLng(50.820645,-0.137376),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var infowindow =  new google.maps.InfoWindow({
        content: ''
    });

    // loop over our array
    for (i = 0; i < arrDestinations.length; i++) {
        // create a marker
        var marker = new google.maps.Marker({
            title: arrDestinations[i].title,
            position: new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lon),
            map: map
        });

        // add an event listener for this marker
        bindInfoWindow(marker, map, infowindow, "<p>" + arrDestinations[i].description + "</p>");
    }
}

function bindInfoWindow(marker, map, infowindow, html) {
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(html);
        infowindow.open(map, marker);
    });
} 

google.maps.event.addDomListener(window, 'load', initialize);
</script>
樱花坊 2024-12-15 22:34:24
function yourlistener(usedMarker)
{
    // in the var usedMarker you have the reference to the single marker
}

for(var x=0;x<markers.length;x++)
(function(marker){

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

)(markers[x]);

像这样的东西?希望这有帮助

function yourlistener(usedMarker)
{
    // in the var usedMarker you have the reference to the single marker
}

for(var x=0;x<markers.length;x++)
(function(marker){

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

)(markers[x]);

something like this? hope this helps

浮萍、无处依 2024-12-15 22:34:24

您的意思是 marker 变量是一个标记数组吗?或者您的意思是您拥有的代码对于每个标记都是重复的?因为如果是后者,那么在每次调用 addListener 时,this 都会引用相关标记。

评论后更新

好的,那么您可以使用一个仅循环 marker1 的函数:

function setVisible(marker) {
    for(var i=0; i<markers1.length; i++) {
        if(marker==markers1[i]) {
            markers2[i].setVisible(true);
        } else {
            markers2[i].setVisible(false);
        }
    }
}   

然后每个单独的点击侦听器定义将如下所示:

google.maps.event.addListener(marker, 'click', function() {
    setVisible(this);
});

但是,您不希望执行类似的操作 10 次,因此您需要将其放入如下模式:

for(var i=0; i<marker1Data.length; i++) {
    marker = new google.maps.Marker({
        map: theMap,
        position: marker1Data[i].latLng,
        visible: true
    })

    marker1.push(marker);

    google.maps.event.addListener(marker, 'click', (function(marker) {
        return function() {
            setVisible(marker);
        }
    })(marker));
}

其中 marker1Data 只是 LatLng 对象的数组,用于定义 marker1 中每个标记的位置代码>.当然还有 marker2 的 for 循环,但使用 visible: false

Do you mean that the marker variable is an array of markers? Or do you mean that the code you have is duplicated for each marker? Because if the latter is the case, then in each call to addListener, this refers to the marker in question.

Update after comments

Ok, then you can use a function that just loops through your marker1:

function setVisible(marker) {
    for(var i=0; i<markers1.length; i++) {
        if(marker==markers1[i]) {
            markers2[i].setVisible(true);
        } else {
            markers2[i].setVisible(false);
        }
    }
}   

Then each individual click listener definition will look like this:

google.maps.event.addListener(marker, 'click', function() {
    setVisible(this);
});

However, you don't want to do something like that 10 times, so you need to put it in a pattern like this:

for(var i=0; i<marker1Data.length; i++) {
    marker = new google.maps.Marker({
        map: theMap,
        position: marker1Data[i].latLng,
        visible: true
    })

    marker1.push(marker);

    google.maps.event.addListener(marker, 'click', (function(marker) {
        return function() {
            setVisible(marker);
        }
    })(marker));
}

Where marker1Data is just an array of LatLng objects that define the location of each marker in marker1. And of course a for loop for marker2, but with visible: false.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文