select icon - Mapbox
select an icon that comes from mapbox studio in a Map canvas
by M J Khan
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Select icons in a map</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.3.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.3.0/mapbox-gl.css' rel='stylesheet' />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<style>
</style>
<div id='map'></div>
</body>
</html>
JavaScript
function initPage(mapboxgl) {
var isDraggable = false;
var selectedSymbol = {};
mapboxgl.accessToken = 'pk.eyJ1IjoicGxheW1hcHMiLCJhIjoiY2pxdW91Mmt3MGRiajQ0bXF0bjNkZGlzNiJ9.D8WVzHCcxCgZYCkB7M-XWQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-65.017, -16.457],
zoom: 7
});
let findInCanvas = (e) => {
var layerX = e.layerX;
var layerY = e.layerY;
var features = map.queryRenderedFeatures([layerX, layerY], {});
if (features && features.length > 0) {
var symbols = getSymbolsWithPoint(features);
if (symbols.length > 0) {
if (selectedSymbol !== symbols[(symbols.length - 1)]) {
isDraggable = true;
if (canvas.style.cursor == '' || canvas.style.cursor == 'auto') {
canvas.style.cursor = 'pointer';
}
selectedSymbol = symbols[(symbols.length - 1)];
map.on('click', symbolSelected);
}
}
else
clearSelectedSymbol();
}
else
clearSelectedSymbol();
};
let clearSelectedSymbol = () => {
if (isDraggable) {
isDraggable = false;
selectedSymbol = null;
canvas.style.cursor = 'auto';
map.off('click', symbolSelected);
}
};
let symbolSelected = (e) => {
if (selectedSymbol == null) {
return;
}
map.off('click', symbolSelected);
...