How can I add an event listener to a mapbox image/raster layer? - mapbox

I am trying to add an event listener to an image layer with mapbox gl, but it doesn't seem to work, is it even possible with this type of layer? Here is a codepen demonstrating the problem:
https://codepen.io/anon/pen/drBdLm
var mapStyle = {
'version': 8,
'sources': {},
'layers': []
}
var map = new mapboxgl.Map({
container: 'map',
maxZoom: 5,
minZoom: 1,
zoom: 5,
center: [-75.789, 41.874],
style: mapStyle
})
map.on('load', function() {
map.addSource('firstim', {
type: 'image',
url: 'https://small-systems.org/dev/093-hvb/cms/site/assets/files/1104/6_umspannwerk_sellerstrasse.700x0.jpg',
coordinates: [
[-80.425, 46.437],
[-71.516, 46.437],
[-71.516, 37.936],
[-80.425, 37.936]
]
})
map.addLayer({
id: 'images',
type: 'raster',
source: 'firstim',
paint: { 'raster-opacity': 1 }
})
map.on('click', function (e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['images'] });
var clusterId = features[0];
// console.log(clusterId)
});
map.on('click', 'images', function (e) {
console.log(e)
});
})
I've tried adding a an event on the layer with map.on('click', layerID, function), but it does't work. Neither does using queryRenderedFeatures.
Thanks for any help.

This is not implemented yet https://github.com/mapbox/mapbox-gl-js/issues/1404.
As a workaround you'll need to listen to all click events and then do your own test to see if the click is within the bounds of your image.

Related

How to have two mapbox raster layers with different opacities?

Im using Mapbox GL API, and I run into the issue that if I add 2 tile layers, that the opacity of the second layer in the paint object is ignored. Does anyone have any idea why this is? In the browser both tile layers have opacity 1.
let style1 = {
id: "source1-tile",
type: "raster",
source: "source1",
paint: {
"raster-opacity": 1.0
},
}
this.map.addLayer(style1);
let style2 = {
id: "source2-tile",
type: "raster",
source: "source2",
paint: {
"raster-opacity": 0.5
},
}
this.map.addLayer(style2);
// print result
console.log(this.map.getStyle().layers)
// this shows the following:
/*
[
{
id: "source1-tile"
paint: Object { "raster-opacity": 1 }
source: "source1"
type: "raster"
},
{
id: "source2-tile"
source: "source2"
type: "raster"
}
]
*/
Pay attention to add layers in map.load event. I've made this example based on mapbox-gl examples. Easily You could add more raster layers with different opacity.
mapboxgl.accessToken = 'pk.eyJ1IjoibHN0aXoiLCJhIjoiY2s5dGtnNTZ2MWVybzNobjEyam0yd2E3MyJ9.6dCvGbS93SKGMbOqZA4Qag';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [-87.62, 41.86],
zoom: 9
});
map.on('load', () => {
map.addSource('chicago', {
'type': 'raster',
'url': 'mapbox://mapbox.u8yyzaor'
});
map.addLayer({
'id': 'chicago',
'source': 'chicago',
'type': 'raster'
});
map.setPaintProperty(
'chicago',
'raster-opacity',
0.5
);
});

Highlighting Fill-Extrude Features on Hover after tilting?

I want to highlight fill-extrusion features when hovered over them.
The styling related to this is straight-forward using expressions and feature state, but I am having trouble retrieving the correct features.
There is code available online to change the feature state when hovered over, and it seems straight-forward enough, so I adapted it:
var hover_id = null;
const feature_state = { hover: true }
map.on('mousemove', '3d-buildings', (e) => {
// Get features under cursor, following render order
const features = map.queryRenderedFeatures(e.point);
// Check that features are not empty
if (features.length > 0) {
// Clean up previously hovered feature
if (hover_id) {
map.removeFeatureState({source: "composite", sourceLayer: 'building', id: hover_id});
}
// Set feature state of the new hovered feature
hover_id = features[0].id;
map.setFeatureState({source: 'composite', sourceLayer: 'building', id: hover_id}, feature_state);
console.log(hover_id)
}
});
While this works well initially, it stops working as soon as I tilt the camera using the right mouse button. After tilting, the foremost element no longer gets selected (something else seems to get selected and an ID gets printed out, but nothing shows up on the map and no error is thrown).
On a related note, the correct feature only gets selected after zooming in quite far - there is a large zoom range where the buildings already get rendered to the screen, but seem to not get picked up by queryRenderedFeatures. Is this expected behaviour?
Expected behaviour:
map.queryRenderedFeatures(...)[0] selects the foremost feature, independent of the camera tilt.
What could be a possible reason for the camera tilt influencing the feature selection? Is this a bug or am I misusing the API?
I think the issue you’re facing has nothing to do with tilt but with the fact that you’re adding and removing the state instead of changing the value of the state. The state must be declared in the layer definition, change the color with a expression, and then you only need to change the value of the state.
Here you have a fiddle I have created to show how to change color of fill extrusions on mouse over/out
Relevant code is this:
let mapConfig = {
NYC: {
origin: [-74.044514, 40.689259, 39],
center: [-74.0137, 40.70346, 0],
zoom: 16.2,
pitch: 60,
bearing: 35
}
}
mapboxgl.accessToken = 'PUT YOUR TOKEN HERE';
let point = mapConfig.NYC;
var map = new mapboxgl.Map({
style: 'mapbox://styles/mapbox/streets-v11',
center: point.center,
zoom: point.zoom,
pitch: point.pitch,
bearing: point.bearing,
container: 'map',
antialias: true,
hash: true
});
map.on('style.load', function() {
if (map.getSource('composite')) {
map.addLayer({
'id': '3d-buildings',
'source': 'composite',
'source-layer': 'building',
'type': 'fill-extrusion',
'minzoom': 14,
'paint': {
'fill-extrusion-color': [
'case',
['boolean', ['feature-state', 'hover'], false],
'#ff0000',
'#ddd'
],
'fill-extrusion-height': ["number", ["get", "height"], 5],
'fill-extrusion-base': ["number", ["get", "min_height"], 0],
'fill-extrusion-opacity': 1
}
}, 'road-label');
}
let fHover;
map.on('mousemove', function(e) {
//157001066
var features = map.queryRenderedFeatures(e.point, {
layers: ['3d-buildings']
});
if (features[0]) {
mouseout();
mouseover(features[0]);
} else {
mouseout();
}
});
map.on('mouseout', function(e) {
mouseout();
});
function mouseout() {
if (!fHover) return;
map.getCanvasContainer().style.cursor = 'default';
map.setFeatureState({
source: fHover.source,
sourceLayer: fHover.sourceLayer,
id: fHover.id
}, {
hover: false
});
}
function mouseover(feature) {
fHover = feature;
map.getCanvasContainer().style.cursor = 'pointer';
map.setFeatureState({
source: fHover.source,
sourceLayer: fHover.sourceLayer,
id: fHover.id
}, {
hover: true
});
}
});
If this answer solves your question, please mark it as answer accepted in that way it will also help other users to know it was the right solution.
#jscastro This works fine: My requirement is I need to change the color of few buildings with lat and lng. I have achieved getting buildings id's from lat and lng by using below API
https://api.mapbox.com/v4/mapbox.mapbox-streets-v8,mapbox.mapbox-terrain-v2/tilequery/55.26365875255766,25.188400365955193.json?radius=30&limit=10&dedupe&access_token=.
I am facing one issue here, The colors are changing only after zoom level 17. I want to change the color on zoom level 15.
map.on("style.load", function () {
if (map.getSource("composite")) {
const layers = map.getStyle().layers;
const labelLayerId = layers.find(
(layer) => layer.type === "symbol" && layer.layout["text-field"]
).id;
map.addLayer(
{
id: "3d-buildings",
source: "composite",
"source-layer": "building",
filter: ["==", "extrude", "true"],
type: "fill-extrusion",
minzoom: 15,
zoom: 15,
pitch: 60,
bearing: -60,
layout: {
// Make the layer visible by default.
visibility: "visible",
},
paint: {
"fill-extrusion-color": [
"case",
["boolean", ["feature-state", "hover"], false],
"#00ff00",
"#AED0EC",
],
"fill-extrusion-height": [
"interpolate",
["linear"],
["zoom"],
15,
0,
15.5,
["get", "height"],
],
"fill-extrusion-base": [
"interpolate",
["linear"],
["zoom"],
15,
0,
15.05,
["get", "min_height"],
],
"fill-extrusion-opacity": 1,
},
},
labelLayerId
);
}
map.getCanvasContainer().style.cursor = "pointer";
map.setFeatureState(
{
source: "composite",
sourceLayer: "building",
id: "4411722601841895",
},
{
hover: true,
}
);
map.getCanvasContainer().style.cursor = "pointer";
map.setFeatureState(
{
source: "composite",
sourceLayer: "building",
id: "1315660041727095",
},
{
hover: true,
}
);
map.getCanvasContainer().style.cursor = "pointer";
map.setFeatureState(
{
source: "composite",
minzoom: 15,
sourceLayer: "building",
id: "3957345234349675",
},
{
hover: true,
}
);
map.getCanvasContainer().style.cursor = "pointer";
map.setFeatureState(
{
source: "composite",
sourceLayer: "building",
id: "5328485811",
},
{
hover: true,
}
);
});

Leaflet how to filter markers

so I'm gonna show two things,
1) This is the image
2) This is my code:
This is my code:
// center of the map
var center = [14.240861626831018, 121.12966240455648];
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osm = L.tileLayer(osmUrl,
{
maxZoom: 17,
minZoom:13
}),
map = new L.Map('map',
{
attributionControl: false,
center: new L.LatLng(14.240861626831018, 121.12966240455648), zoom: 13
}),
drawnItems = L.featureGroup().addTo(map);
L.control.layers({
'osm': osm.addTo(map),
"google": L.tileLayer('http://www.google.cn/maps/vt?lyrs=s#189&gl=cn&x={x}&y={y}&z={z}',
{
attribution: 'google',
maxZoom: 20,
minZoom:13
}),
"monolight": L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw',
{
attribution: 'google',
maxZoom: 20,
minZoom:13,
id: 'mapbox.light'
}),
"dark": L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}{r}.png',
{
attribution: '© OpenStreetMap © CartoDB',
subdomains: 'abcd',
maxZoom: 20,
minZoom:13
})
}, { 'Enable markers': drawnItems },
{
position: 'bottomleft',
collapsed: true
}).addTo(map);
map.addControl(new L.Control.Draw({
position: 'bottomleft',
edit: {
edit:false,
remove: true,
featureGroup: drawnItems,
poly: {
allowIntersection: false
}
},
draw: {
polygon: {
allowIntersection: false,
showArea: true
},
// disable toolbar item by setting it to false
polygon: true,
polyline:true,
circle: false,
rectangle:false,
marker: true,
circlemarker: false
}
}));
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
map.addLayer(layer);
if (type === 'marker') {
layer.bindPopup('LatLng: ' + layer.getLatLng()).openPopup();
}
});
I was wondering if separating the markers using checkbox is possible?
I mean I want to make separate checkboxes for each marker. Like if I only want to show the lines, I can hide the markers and polygons. Sorry for the mess. Thanks!

Simply adding points tileset layer with Mapbox js

I need to simply add a tileset of points.
No idea why I'm not able to do this.
Here's the fiddle, below is the js code.
https://jsfiddle.net/qaehnvs9/3/
mapboxgl.accessToken = 'pk.eyJ1IjoibW9sbHltZXJwIiwiYSI6ImNpazdqbGtiZTAxbGNocm0ybXJ3MnNzOHAifQ.5_kJrEENbBWtqTZEv7g1-w'
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
hash: true,
center: [0,0],
zoom: 1,
pitchWithRotate: false,
})
/////////////////////////////////////////////////////////////
//Global Settlements
/////////////////////////////////////////////////////////////
map.on('load', function () {
map.addLayer({
'id': 'global_settlements_id',
'source': {
'type': 'vector',
'url': 'mapbox://nittyjee.c9okffto'
},
//'source-layer': 'shapefile_export-4f28wr',
'source-layer': 'shp-2lsmbo',
'type': 'symbol',
'maxzoom': 6,
'layout': {
'symbol-placement': 'point',
}
});
});
For dots/points, I needed to add it as a circle type.
Updated fiddle: https://jsfiddle.net/qaehnvs9/4/
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
hash: true,
center: [0,0],
zoom: 1,
pitchWithRotate: false,
})
/////////////////////////////////////////////////////////////
//Global Settlements
/////////////////////////////////////////////////////////////
map.on('load', function () {
map.addLayer({
'id': 'global_settlements_id',
'type': 'circle',
'source': {
type: 'vector',
url: 'mapbox://nittyjee.c9okffto'
},
'source-layer': 'shp-2lsmbo',
'paint': {
'circle-radius': 4,
'circle-color': '#e55e5e'
}
});
});

Leaflet Draw, Only marker showing, Lines and Polygons not visibile

I'm trying to add the Leaflet Draw library / control.
I can add a marker, and it persists (and stays visible). But when I add a line or polygon they aren't visible (persisted though if I inspect the .layers, also check the screenshot. The element seems to be there, but it just isn't visible).
Any guidance would be highly appreciated!
Edit: I'm using the following code to initialize the map:
var elem = angular.element('#datasetLeafletMap'); //using Angular
console.log('initting map', elem[0]);
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osmAttrib = '© OpenStreetMap contributors',
osm = L.tileLayer(osmUrl, { maxZoom: 18, attribution: osmAttrib });
var map = new L.Map(elem[0], { layers: [osm], center: new L.LatLng(52.105289405897, 5.2629891004852425), zoom: 13 });
console.log('map ready');
var drawnItems = new L.FeatureGroup();
var coords = [new L.latLng(51.2, 4.5), new L.latLng(51.2, 4.6), new L.latLng(51.2, 4.9)];
var poly = new L.Polyline(coords, {
color: 'blue',
opacity: 1,
weight: 5
});
drawnItems.addLayer(poly);
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
draw: {
position: 'right',
polygon: {
title: 'Polygon',
allowIntersection: false,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#bada55'
},
showArea: true
},
polyline: {
metric: false
},
circle: {
shapeOptions: {
color: '#662d91'
}
}
},
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('A popup!');
}
drawnItems.addLayer(layer);
console.log('adding layer', layer, drawnItems);
});