2

I have a custom line in mapbox that displays a popup when you click it, how can I make it so it shows only when you hover it ? I changed from "click" to "mouseenter" but it did not closed the popup. What needs changing so when I hover over this line it shows the popup and then it closes when leaving the line/popup?

Here is a jsfiddle example :

JS

mapboxgl.accessToken = '';
 var map = new mapboxgl.Map({
 container: 'map',
 style: 'mapbox://styles/mapbox/streets-v11',
 center: [-0.066985, 51.503363],
 zoom: 9
 });
map.on('load', function() {
 map.addSource('routeThree', {
 'type': 'geojson',
 'data': {
 'type': 'Feature',
 'properties': {},
 'geometry': {
 'type': 'LineString',
 'coordinates': [
 [-0.066985, 51.503363],
 [-3.550610, 40.390555 ],
 [-77.140217, 38.801481],
 [-118.175979, 34.008447]
 ]
 }
 }
 });
 map.addLayer({
 'id': 'routeThree',
 'type': 'line',
 'source': 'routeThree',
 'layout': {
 'line-join': 'round',
 'line-cap': 'round'
 },
 'paint': {
 'line-color': '#04A5BD',
 'line-width': 8
 }
 });
 map.on('click', 'routeThree', function(e) {
 new mapboxgl.Popup()
 .setLngLat(e.lngLat)
 .setHTML("<h2>This is the third line that will explain something</h2>")
 .addTo(map);
 
 });
 
 
 });
asked Jul 10, 2020 at 9:55

1 Answer 1

4

You'd need to add the closing as part of a mouseleave event

map.on('mouseleave', 'routeThree', function() {
 popup.remove();
});

Note that this assumes a template popup var above function scope to get accessed, i.e.

var popup = new mapboxgl.Popup({
 <options>
});

See the official example for more on the general usage.

answered Jul 10, 2020 at 11:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.