Search code examples
javascriptc#asp.net-mvcbing-mapspushpin

Bing map pushpin click event handler applies only last one


I've the following Bing map generated from my application -

enter image description here

The green pushpin added to the map after the red pushpins. Every pushpin has a click handler which opens an infobox. My problem is whatever pushpin I click on, it opens only infobox for the green pushpin.

Here is my code-

    var center = new Microsoft.Maps.Location(24.3636, 88.6241);
    var map = new Microsoft.Maps.Map(document.getElementById('myMap'), { center:center, zoom: 7 });

    var color; var description;

    @foreach (var item in Model.MapData)
    {
        <text>

        var location = new Microsoft.Maps.Location(@item.Latitude,@item.Longitude);
        var pushpin = new Microsoft.Maps.Pushpin(location, { color: color });

        map.entities.push(pushpin);

        var infobox = new Microsoft.Maps.Infobox(location, {
            title: '@item.DtwId',
            description: '@item.Desc',
            visible: false 
        });

        Microsoft.Maps.Events.addHandler(pushpin, 'click', function () {
            infobox.setOptions({ visible: true });
        });

        infobox.setMap(map);


        </text>
    }

What did I miss here?


Solution

  •  var location = new Microsoft.Maps.Location(@item.Latitude,@item.Longitude);
            var pushpin = new Microsoft.Maps.Pushpin(location, { color: color });
    
            pushpin.metadata = {
               title: '@item.DtwId',
            description: '@item.Desc',
                franchiseNumber: 1
            };
    
            Microsoft.Maps.Events.addHandler(pushpin, 'click', pushpinClicked);
    
            map.entities.push(pushpin);
    
    
        function pushpinClicked(e) {
    
            var infobox = new Microsoft.Maps.Infobox(e.target.getLocation(), {
                title: e.target.metadata.title,
                description: e.target.metadata.description,
                visible: true
            });
    
            infobox.setMap(map);