console
mapboxgl.accessToken = 'pk.eyJ1IjoiemhhbmdjaGVuMTk4OCIsImEiOiJjajYyeHMybzUxZDNlMzBqeHpxY3F4OTI0In0.GEHyHKuNf-hgOckcgOtYNg';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-v9',
center: [-91.874, 42.76],
zoom: 12
});
const geojson={
"id": "4bd43768e6ca24a2d2182e67f19e1993",
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
[
-91.8777765502924,
42.773960248879916
],
[
-91.84378759765568,
42.77421226051405
],
[
-91.84378759765568,
42.745224200524746
],
[
-91.87829153442324,
42.74497207096152
],
[
-91.8777765502924,
42.773960248879916
]
]
],
"type": "Polygon"
}
}
map.on('load',()=>{
map.addSource('maine', {
'type': 'geojson',
'data': geojson
});
map.addLayer({
'id': 'maine',
'type': 'fill',
'source': 'maine',
'layout': {},
'paint': {
'fill-color': '#0080ff',
'fill-opacity': 0.5
}
});
})
const draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
},
defaultMode: 'draw_polygon'
});
map.addControl(draw);
map.on('draw.create', updateArea);
map.on('draw.delete', updateArea);
map.on('draw.update', updateArea);
map.on('draw.modechange', (e)=>{
console.log(1111)
});
function updateArea(e) {
const data = draw.getAll();
const answer = document.getElementById('calculated-area');
if (data.features.length > 0) {
const area = turf.area(data);
const rounded_area = Math.round(area * 100) / 100;
answer.innerHTML = `<p><strong>${rounded_area}</strong></p><p>square meters</p>`;
} else {
answer.innerHTML = '';
if (e.type !== 'draw.delete')
alert('Click the map to draw a polygon.');
}
}
<div id="map"></div>
<div class="calculation-box">
<button onclick='click()'>编辑</button>
<p>Click the map to draw a polygon.</p>
<div id="calculated-area"></div>
</div>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
.calculation-box {
height: 75px;
width: 150px;
position: absolute;
bottom: 40px;
left: 10px;
background-color: rgba(255, 255, 255, 0.9);
padding: 15px;
text-align: center;
}
p {
font-family: 'Open Sans';
margin: 0;
font-size: 13px;
}