在Bing地图中触发点击事件

4

我在Bing Maps的点击事件上遇到了一些问题。 我有一个商店数组,我可以毫无问题地放置所有的图钉和点击事件(以打开信息框)。

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);
}

现在的问题是,当用户通过搜索页面进入页面时,会自动添加一个带有 id 的哈希标记,例如 /stores#id123。
我希望地图能自动打开具有该 id 的框,因此我添加了以下代码。
var hash = window.location.hash;
hash = hash.replace("#", "");
if(hash.length>0){
    var pin = $('img[src*="?'+hash+'"]').parent();
    pin.trigger('click');
}

但它就是不能工作。我也尝试过。
Microsoft.Maps.Events.invoke(a, 'click');

但是什么都没有发生,有人有解决办法吗,可以触发点击事件吗?
谢谢。

哈希值是否意味着/storesid123? - Daemedeor
另外,你说的“它就是不工作”是什么意思?你能更具体地描述一下或者说出现了哪些错误吗? - Daemedeor
当我说“它就是不起作用”时,我的意思是“trigger('click')”无法运行打开盒子的事件“Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);”。 - Kup
1
问题不在哈希上,而是Bing使用的事件处理程序。我无法访问它(不知道如何触发它)。 - Kup
1个回答

4
Microsoft.Maps.Events.invoke 函数需要一个 实体对象,而不是 Html 元素。实体可以是以下任意一种类型:信息框多边形折线图钉瓦片图层实体集合

话虽如此,您可以考虑以下方法来查找图钉

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;
}

使用方法

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 });
}

2
这是正确的。去年我创建Bing Maps热力图应用程序时也遇到了同样的问题,而这就是我解决问题的方法。 - Michael Mahony
1
我不得不稍微调整一下,但它起作用了,谢谢。 - Kup
1
我在尝试使用未定义的目标时遇到了问题。使用“this”解决了我的问题。感谢提供这个好的示例。 - puddinman13

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接