我有脚本在地图上显示标记
这是代码
我需要在标记悬停时显示弹出窗口
例如,我尝试这样做,因此它需要在宜必思伦敦巴金酒店工作。
但这不起作用
map.on('mouseover', 'Ibis London Barking', function(e) {
alert("Hover");
});
官方文档说我需要这样的代码
map.on('mouseenter', 'places', function(e) {******}):
但是他们添加了addLayer()
中的标记,而我没有。如何解决这个问题?
答案 0 :(得分:2)
可能的解决方案是添加所需的图层。例如this
我略微更改了您的代码以生成类似the example from the docs
所示的图层对象map.on("load", function() {
const starImage = '<img class="star-image" style="height:20px;width:20px;">';
const layer = {
"id": "places",
"type": "symbol",
"layout": {
"icon-image": "{icon}-15",
"icon-allow-overlap": true
},
"source": {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": json.map(function(item){
return {
"type": "Feature",
"properties": {
"description": `<div class="map-card__wrapper">
<div class="map-card__image-container">
<div class="map-card__image" style="background: url(${item.pictures[0].url});"></div>
</div>
<div class ="map-card__content-container ">
<div class ="map-card__title">${item.name}</div>
<p class="map-card__address">${item.address1}</p>
<div class ="map-card__review">${starImage.repeat(item.rating)}</div>
</div>
</div>`,
"icon": "star" //probably want to change
},
"geometry": {
"type": "Point",
"coordinates": [item.lng, item.lat]
}
}
})
}
}
};
map.addLayer(layer);
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false,
offset: 5
});
map.on('mouseenter', 'places', function(e) {
console.log(e)
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = 'pointer';
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.description;
// Ensure that if the map is zoomed out such that multiple
// copies of the feature are visible, the popup appears
// over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
map.on('mouseleave', 'places', function() {
map.getCanvas().style.cursor = '';
popup.remove();
});
});
答案 1 :(得分:0)
尝试一下:
map.on('load', function() {
// Create a popup
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
function showPopup(e) {
// Change the cursor
map.getCanvas().style.cursor = 'pointer';
// Show the popup
popup.setLngLat(e.features[0].geometry.coordinates)
.setHTML(checkEmpty(e.features[0].properties.name))
.addTo(map);
}
function hidePopup() {
map.getCanvas().style.cursor = '';
popup.remove();
}
function checkEmpty(info) {
return (info) ? info : "No data";
}
map.on('mouseenter', 'places', showPopup);
map.on('mouseleave', 'places', hidePopup);
});