Reputation: 13
I've adapted the Mapbox example for a popup on hover using another example for a popup on click, and everything is working great except that the popup won't close on "mouseleave". I must have done something wrong when I combined the two examples but I can't find the answer anywhere. Please help!
<html>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibWFyeXNoYWZmZXIiLCJhIjoiY2poNnkwZ3pvMDI5ZzJ4cWUyY296NnNjdCJ9.PgJCuPhDYgm8oCmsZlAeQA'; // replace this with your access token
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/maryshaffer/cjh6yf7c30apg2sotfzmyf2je', // replace this with your style URL
});
// code from the next step will go here
map.addControl(new mapboxgl.NavigationControl());
map.on('mouseenter', 'pilgrimage-sites-markers', function(e) {
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseenter', 'pilgrimage-sites-markers', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['pilgrimage-sites-markers'] // replace this with the name of the layer
});
if (!features.length) {
return;
}
var feature = features[0];
var popup = new mapboxgl.Popup({
closeOnClick: false,
offset: [0, -15] })
.setLngLat(feature.geometry.coordinates)
.setHTML('<h3>' + feature.properties.title + '</h3><p>' + feature.properties.description + '</p><h4><a href=\"' + feature.properties.link + '\">Learn More</a></h4>')
.setLngLat(feature.geometry.coordinates)
.addTo(map);
});
map.on('mouseleave', 'pilgrimage-sites-markers', function() {
map.getCanvas().style.cursor = '';
popup.remove();
});
</script>
</body>
</html>
Upvotes: 1
Views: 2193
Reputation: 29157
The problem is that the popup
variable is declared locally inside the handler of the map.on('mouseenter')
event.
And, accordingly, it is not defined inside the handler of the map.on('mouseleave')
event.
So you need to move the declarations of the popup
variable to the scope of both functions.
For example: https://jsfiddle.net/e5j10x1o/
Upvotes: 2