Reputation: 11
I want to display the popup about the marker on hover (not click). I have looked at all the examples on Mapbox (https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) -
however the issue in the example is its pulling the locations and descriptions from a layer in the script... where as I would like it to show the data from my dataset layer ['mydata']
The code below works for clicking on the marker - I simply would like it to work on hover.
<script>
mapboxgl.accessToken = 'example-token'; // replace this with your access token
var map = new mapboxgl.Map({
container: 'map',
style: 'example-style' // replace this with your style URL
});
// code from the next step will go here
map.on('click', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['pillbox-data'] // replace this with the name of the layer
});
if (!features.length) {
return;
}
var feature = features[0];
var popup = new mapboxgl.Popup({
offset: [0, -15]
})
.setLngLat(feature.geometry.coordinates)
.setHTML('<h3>' + feature.properties.title + '</h3><p>' + feature.properties.description + '</p>')
.setLngLat(feature.geometry.coordinates)
.addTo(map);
});
map.addControl(new MapboxGeocoder({
accessToken: mapboxgl.accessToken
}));
</script>
Upvotes: 1
Views: 6128
Reputation: 21
You'll want to use on 'mousemove' instead of on 'click'. After you initialize your map, insert this code. It's a Mapbox tileset, so your access token should work.
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false
});
map.on('load', function() {
// Add the source to query. In this example we're using
// county polygons uploaded as vector tiles
map.addSource('counties', {
"type": "vector",
"url": "mapbox://mapbox.82pkq93d"
});
map.addLayer({
"id": "counties",
"type": "fill",
"source": "counties",
"source-layer": "original",
"paint": {
"fill-outline-color": "rgba(0,0,0,0.1)",
"fill-color": "rgba(0,0,0,0.1)"
}
}, 'place-city-sm'); // Place polygon under these labels.
map.on('mousemove', 'counties', function(e) {
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = 'pointer';
// Single out the first found feature.
var feature = e.features[0];
// Display a popup with the name of the county
popup.setLngLat(e.lngLat)
.setText(feature.properties.COUNTY)
.addTo(map);
});
map.on('mouseleave', 'counties', function() {
map.getCanvas().style.cursor = '';
popup.remove();
});
});
Upvotes: 1