3

How to listen for different click events in mapbox using JavaScript? The following is the code for displaying a map using map box.

Can someone suggest how to listen to click events that differentiates land from water bodies?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display a map on a webpage</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
    mapboxgl.accessToken = 'pk.eyJ1IjoiZGphZWJvIiwiYSI6ImNrbzJoYjhodTAxeDUyb211eTF2anZ0bmQifQ.62m9LNQhEPZNCwqxEW9pPQ';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11', // style URL
center: [-74.5, 40], // starting position [lng, lat]
zoom: 9 // starting zoom
});
</script>
 
</body>
</html>

I'm being able to listen to click events using the following code:

     map.on('click', (e) => {
        console.log(e.lngLat)
      })

But is there a way to differentiate coordinates land from water bodies?

1 Answer 1

3

if you try this:

map.on('load', function () {
    let style = map.getStyle();
})

then you can see all the details about the style such as sources, layers, glyphs and etc . Also for listening to click events on different layers, you can just use:

 map.on('click', 'land', function (e) {
     // some code
 });

or you can query the rendered features within multiple layers by code below:

map.on('click', function (e) {
    let featureSelected = map.queryRenderedFeatures(e.point, {layers: ['land', 'water']
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.