Reputation: 1
I try to make a chroropleth map with mapbox gl js. It kind of works with the code below, but it's also a bit "buggy". When i hover over the map the popup is only sometimes there.
Is there a way to show the popup only in the middle of each feature?
I am new to mapbox and javascript and this is my first help request here, so apologies for any inconveniences.
mapboxgl.accessToken = 'xxx';
const map = new mapboxgl.Map({
container: 'map',
style: 'xxx',
center: [8.798, 53.122],
zoom: 8.15
});
map.on('load', () => {
map.addSource('members', {
type: 'vector',
url: 'xxx'
});
map.addLayer({
'id': 'members_1',
'type': 'fill',
'source': 'members',
'source-layer': 'final_mitgliederV1_1-bcbjyn',
'paint': {
'fill-opacity': 0
}
},
);
// Create a popup, but don't add it to the map yet.
const popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
map.on('mouseenter', 'members_1', (e) => {
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = 'pointer';
// Copy coordinates array.
const coordinates = e.features[0].geometry.coordinates.slice();
const description = e.features[0].properties.m_Mitglieder;
var members = e.features[0].properties.m_members;
var description2 = "" +
"<div id='header'>" +
"<div class='tooltip'>" + members + "</div>" + "Mitglieder: ";
// Ensure that if the map is zoomed out such that multiple
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(e.lngLat).setHTML(description2).addTo(map);
});
map.on('mouseleave', 'members_1', () => {
map.getCanvas().style.cursor = '';
popup.remove();
});
});
Upvotes: 0
Views: 182
Reputation: 1
Found the mistake: it has to be 'mousemove' instead of 'mouseenter'
Upvotes: 0