While adding multiple pushpins in Bing Maps the infobox always takes the last element

652 Views Asked by At

I want to add multiple infobox to my bing maps which will load automatically on startup and not on click event. Suppose i have 3 pushpins so 3 infobox will pop up automatically with the data say for eg 1st infobox will contain james, 2nd mark, 3rd etc etc . As of now if i put it in a loop and try to add it always takes the last value

 for (var i = 0; i < json.length; i++) {
                          var pinInfoBox;  //the pop up info box
                          var infoboxLayer = new Microsoft.Maps.EntityCollection();
                          var pinLayer = new Microsoft.Maps.EntityCollection();
                          var loc = jsonData.location[i];
                           var pushpinOptions = {icon: 'xxx.png', width: 80, height: 80, offset: new Microsoft.Maps.Point(0, 15)};
                         var infoboxOptions = {showCloseButton: true, visible:false };
                          pinInfobox = new Microsoft.Maps.Infobox(map.getCenter(), infoboxOptions );
                           pinInfobox.setHtmlContent('<div class="arrow_box"><div class="content" id="content">'+loc.name+'</div></div>'); //here the name should keep changing
                          infoboxLayer.push(pinInfobox);
                          var pin = new Microsoft.Maps.Pushpin(latLon,pushpinOptions);
                           pinLayer.push(pin); //add pushpin to pinLayer
                          Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox); //here instead of click event i want the infobox to display automatically on startup
                          map.entities.push(pinLayer);
                          map.entities.push(infoboxLayer);
           }

           function displayInfobox(e) {

        pinInfobox.setOptions({title: e.target.Title, description: e.target.Description,                  visible:true, offset: new Microsoft.Maps.Point(-50,90)});
      pinInfobox.setLocation(e.target.getLocation());
          }
1

There are 1 best solutions below

0
On

Set the options and location of the infoboxes inside of the for loop rather than after it. Then store a reference to each infobox in your Pushpin. Do something like pin.infobox = pinInfobox; and then in your displayInfobox function you can show the infobox by doing:

e.target.infobox.setOptions({visible: true});

That said, if you have a lot of pushpins it is better to have one infobox and update it as needed. Here is a blog post that outlines this approach: https://rbrundritt.wordpress.com/2011/10/13/multiple-pushpins-and-infoboxes-in-bing-maps-v7/