So, I'm trying to get a style layer from the loaded stylemap in mapbox GL but it keeps returning undefined elements. I'm at the end of my wits.
I'm trying to get the underlaying water layer to store in the layers variable so I can alter its properties. For instance, its visibility.
Here's the code:
var layers=map.getLayer('water');
changeinnerHTML(featuresWindow, JSON.stringify(layers, null, 1));
PS - I'm returning to coding after years. I just brushed upon my js again.
PPS: Here's the whole code if you care:
<script>
//Mapbox Access Token
mapboxgl.accessToken = 'pk.eyJ1IjoiYWtzaGF5a2h1cmFuYSIsImEiOiJjaWY3dXdkN3MxMzZ3czZsempwbWc0MnRoIn0.y7jHQWK5lONsJ_6u3EJSTg';
// Select html objects that constantly change into javascript variables. Henceforth known as elementVar
var featuresWindow = document.getElementById('features');
// GLOBAL FUNCTIONS : Functions that are used repeatedly
// Function to change inner HTML of div, span etc elements
function changeinnerHTML(elementVar, newvalue) {
elementVar.innerHTML = newvalue;
return null;
}
// Function to change colours.
function switchColor(myColor, layer) {
map.setPaintProperty(layer, 'fill-color', myColor);
}
// Intialise map
if (!mapboxgl.supported()) {
alert('Your browser does not support Mapbox GL!');
} else {
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/akshaykhurana/cihlwytjz001kb4kqu0b62xq7', //stylesheet location
minZoom: 9, //minimum zoom value
maxZoom: 16, //maximum zoom value
interactive: true
});
}
// Get some layers man.
var layers=map.getLayer();
changeinnerHTML(featuresWindow, JSON.stringify(layers, null, 1));
// Push information to sidebar on mouse hover
map.on('click', function(e) {
map.featuresAt(e.point, {
radius: 5
}, function(err, features) {
if (err) throw err;
changeinnerHTML(featuresWindow1, JSON.stringify(features, null, 2));
});
});
</script>
Not sure if you have figured this out yet but basically you just need to get rid of the "map.getLayer('water')" section.
I'm not sure what you are using this for, as you can set the style to be invisible right in the Mapbox studio editor, but when I change a Layout Property, I do it with a .click(function) like so:
Then all you have to do is add a button or any other item to your HTML with the class "className" and whenever it is clicked, the water layer will become invisible.