Reputation: 79
Is it possible to generate popups in Mapbox from a text-label layer?
The following code generates popups from polygons:
map.on('load', function () {
map.on('mousemove', 'state-shape', function (e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['state-shape'] // the name of the layer
});
if (!features.length) {
return;
}
var feature = features[0];
popup
.setLngLat(e.lngLat)
// .setHTML(e.features[0].properties.name)
.setHTML("<strong>State: </strong>" + feature.properties.STATE_NAME
)
.addTo(map);
});
// Change the cursor to a pointer when the mouse is over the states layer.
map.on('mouseenter', 'state-shape', function () {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'state-shape', function () {
map.getCanvas().style.cursor = '';
popup.remove();
});
I try to do the same thing for the labels layer, but nothing happens.
map.on('load', function () {
map.on('mousemove', 'state-labels', function (e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['state-labels'] // name of the layer
});
if (!features.length) {
return;
}
var feature = features[0];
popup
.setLngLat(e.lngLat)
// .setHTML(e.features[0].properties.name)
.setHTML("<strong>State: </strong>" + feature.properties.STATE_NAME
)
.addTo(map);
});
map.on('mouseenter', 'state-labels', function () {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'state-labels', function () {
map.getCanvas().style.cursor = '';
popup.remove();
});
});
If anyone knows if this is possible through another means, please let me know.
Upvotes: 0
Views: 118
Reputation: 5213
Yes. You can query mapboxgl vector data including text layers.
Here's how to query state-label
layer and show state name in a popup. You had couple of typos in code like state-labels
.
map.once("load", () => {
var popup = new mapboxgl.Popup();
map.on("mousemove", "state-label", function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ["state-label"] // name of the layer
});
if (!features.length) {
return;
}
var feature = features[0];
popup.setLngLat(e.lngLat)
// .setHTML(e.features[0].properties.name)
.setHTML("<strong>State: </strong>" + feature.properties.name)
.addTo(map);
});
map.on("mouseenter", "state-label", function() {
map.getCanvas().style.cursor = "pointer";
});
map.on("mouseleave", "state-label", function() {
map.getCanvas().style.cursor = "";
popup.remove();
});
});
Here's a codepen demonstrating the same: https://codepen.io/manishraj/pen/PowLPVq
Upvotes: 1