mapgl geojson hover with polygon
by Trufi
HTML
<script src="https://jakarta-tiles-3800.web-staging.2gis.ru/sdk/index.js"></script>
<div id="container"></div>
CSS
html,
body,
#container {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
JavaScript
const map = new mapgl.Map('container', {
center: [-96.56, 39.49],
zoom: 4,
key: 'bfd8bbca-8abf-11ea-b033-5fa57aae2de7',
});
map.on('styleload', () => {
map.addLayer({
id: 'state',
type: 'polygon',
filter: ['match', ['sourceAttr', 'name'],
['state'], true, false
],
style: {
color: '#ff000055',
},
});
});
let hoveredFeature;
let polygon;
map.on('mousemove', (ev) => {
if (!ev.targetData || ev.targetData.type !== 'geoJson') {
if (polygon) {
polygon.destroy();
}
return;
}
if (hoveredFeature === ev.targetData.feature) {
return;
}
if (polygon) {
polygon.destroy();
}
polygon = new mapgl.Polygon(map, {
coordinates: ev.targetData.feature.geometry.coordinates,
interactive: true,
color: '#ff0000',
strokeWidth: 0,
});
});
fetch('https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json')
.then(r => r.json())
.then((data) => {
new mapgl.GeoJsonSource(map, {
type: 'geojson',
data,
attributes: {
name: 'state',
},
});
})