Trigger Click Event in Bing Maps

2.4k views Asked by At

I'm having a bit of trouble with the click event on Bing Maps. I've got an array of stores and I can put all the pin and click events (to open a infobox) with no problems

var STORES = [
    {
        id: 123,
        lat: 1.23456789,
        lng: -1.23456789,
        name: 'AEVA'
    },
    ...
]

for (var i = 0; i < STORES.length; i++) {
    var pinOptions: {icon: 'map-pin.png?id'+STORES[i].id, width: 29, height: 52},
        LatLng = new Microsoft.Maps.Location(STORES[i].lat, STORES[i].lng),
        pin = new Microsoft.Maps.Pushpin(LatLng, pinOptions);

    pin.content = '<p>'+STORES[i].name+'</p>';

    Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);

    bing.pinLayer.push(pin);
}

Now the problem is, when the user arrives at the page through the search page, wich basically adds an hashtag with the id, for example /stores#id123

I want the map to open automatically the box with that id, so I've added this code

var hash = window.location.hash;
hash = hash.replace("#", "");
if(hash.length>0){
    var pin = $('img[src*="?'+hash+'"]').parent();
    pin.trigger('click');
}

But it just won't work. I've also tried

Microsoft.Maps.Events.invoke(a, 'click');

But nothing happened, does anyone have any solution, to trigger the event click?

Thanks

1

There are 1 answers

3
Vadim Gremyachev On BEST ANSWER

Microsoft.Maps.Events.invoke function expects entity object and not Html element. An Entity can be any one of the following types: Infobox, Polygon, Polyline, Pushpin, TileLayer, or EntityCollection.

Having said that you could consider the following approach for finding Pushpin:

function findPin(map,storeId)
{
    for(var i = 0; i < map.entities.getLength();i++){
        var entity = map.entities.get(i);
        if(entity.getIcon === undefined) continue;
        var icon = entity.getIcon();  
        if(entity.getIcon() === "map-pin.png?id" + storeId) return entity;
    }
    return null;
}

Usage

var storeId = window.location.hash.replace("#id", "");
if(storeId.length > 0){
    var selectedPin = findPin(bing,storeId);
    Microsoft.Maps.Events.invoke(selectedPin, 'click');
}

where

function displayInfobox(e) {
    infobox.setLocation(this.target.getLocation());
    infobox.setOptions({ visible: true });
}