我有一个页面正在调用返回GeoJson的服务 与以下代码类似:
var usgsEarthquakeUrl = 'http://earthquake.usgs.gov/fdsnws/event/1/query?minmagnitude=3&format=geojson';
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
Microsoft.Maps.GeoJson.readFromUrl(usgsEarthquakeUrl,
function (shapes) {
//Add the shape(s) to the map.
map.entities.push(shapes);
}, 'callback');
});
我希望能够添加一个"点击"或者" mouseover"事件处理程序,以便我可以添加一个信息框,显示有关该引脚的一些信息。
答案 0 :(得分:1)
有两种方法可以解决这个问题:
以下是将事件添加到每个单独形状的方法:
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Your Bing Maps Key',
zoom: 4
});
var infobox = new Microsoft.Maps.Infobox(map.getCenter(), { visible: false });
infobox.setMap(map);
var usgsEarthquakeUrl = 'https://earthquake.usgs.gov/fdsnws/event/1/query?minmagnitude=3&format=geojson';
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
Microsoft.Maps.GeoJson.readFromUrl(usgsEarthquakeUrl, function (shapes) {
//Add click event to each shape.
for(var i = 0, len=shapes.length; i < len; i++){
Microsoft.Maps.Events.addHandler(shapes[i], 'click', showInfobox);
}
//Add shapes to the map.
map.entities.push(shapes);
}, 'callback');
});
function showInfobox(e){
var shape = e.target;
var loc = e.location; //Default to the location of the mouse event to show the infobox.
//If the shape is a pushpin, use it's location to display the infobox.
if(shape instanceof Microsoft.Maps.Pushpin){
loc = shape.getLocation();
}
//Display the infoboc
infobox.setOptions({location: loc, title: shape.metadata.title, visible: true });
}
以下是使用图层(推荐)执行此操作的方法:
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Your Bing Maps Key',
zoom: 4
});
var infobox = new Microsoft.Maps.Infobox(map.getCenter(), { visible: false });
infobox.setMap(map);
var dataLayer = new Microsoft.Maps.Layer();
map.layers.insert(dataLayer);
//Add click event to the layer.
Microsoft.Maps.Events.addHandler(dataLayer, 'click', showInfobox);
var usgsEarthquakeUrl = 'https://earthquake.usgs.gov/fdsnws/event/1/query?minmagnitude=3&format=geojson';
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
Microsoft.Maps.GeoJson.readFromUrl(usgsEarthquakeUrl, function (shapes) {
//Add shapes to the layer.
dataLayer.add(shapes);
}, 'callback');
});
function showInfobox(e){
var shape = e.target;
var loc = e.location; //Default to the location of the mouse event to show the infobox.
//If the shape is a pushpin, use it's location to display the infobox.
if(shape instanceof Microsoft.Maps.Pushpin){
loc = shape.getLocation();
}
//Display the infoboc
infobox.setOptions({location: loc, title: shape.metadata.title, visible: true });
}
这是live sample。