答案 0 :(得分:0)
mapboxgl.Marker
are implemented as simple HTML <div>
elements. You can attach standard event listener to them and toggle the popup manually:
const marker = new mapboxgl.Marker({/* options */});
const markerDiv = marker.getElement();
markerDiv.addEventListener('mouseenter', () => marker.togglePopup());
markerDiv.addEventListener('mouseleave', () => marker.togglePopup());
See docs: https://docs.mapbox.com/mapbox-gl-js/api/#marker#getelement
EDIT: Preventing the popup from opening on click
I tried did some testing, and the only thing reliably working is to call marker.togglePopup()
in your own click handler
map.on('click', event => {
const target = event.originalEvent.target;
const markerWasClicked = markerDiv.contains(target);
marker.togglePopup();
});
Full example: https://jsfiddle.net/am2jwtzg/
答案 1 :(得分:0)
Scarysize答案有效。但是,如果您将鼠标悬停在标记上时单击它,则弹出窗口将关闭,离开标记时,弹出窗口将再次打开。
为防止此行为,您应该使用marker.addTo(map)
和marker.remove()
方法,这些方法由marker.togglePopup()
函数在内部使用:Marker source
togglePopup() {
var popup = this._popup;
if (!popup) return;
else if (popup.isOpen()) popup.remove();
else popup.addTo(this._map);
}
下面的工作示例
mapboxgl.accessToken = 'pk.eyJ1IjoibW9ycGhvY29kZSIsImEiOiJVMnRPS0drIn0.QrB-bpBR5Tgnxa6nc9TqmQ';
var monument = [-77.0353, 38.8895];
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: monument,
zoom: 15
});
// create the popup
var popup = new mapboxgl.Popup(
{offset:[28, 0]}
).setText(
'Construction on the Washington Monument began in 1848.'
);
// create the marker
let marker = new mapboxgl.Marker().setLngLat(monument);
// get the marker element
const element = marker.getElement();
element.id = 'marker'
// hover event listener
element.addEventListener('mouseenter', () => popup.addTo(map));
element.addEventListener('mouseleave', () => popup.remove());
// add popup to marker
marker.setPopup(popup);
// add marker to map
marker.addTo(map);
#map { position:absolute; top:0; bottom:0; width:100%; }
#marker {
background-image: url('https://www.mapbox.com/mapbox-gl-js/assets/washington-monument.jpg');
background-size: cover;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
}
.mapboxgl-popup {
max-width: 200px;
}
<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.28.0/mapbox-gl.css" rel="stylesheet"/>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.28.0/mapbox-gl.js"></script>
<div id="map"></div>