I am new to javascript and Im not very good at it yet. Im using javascript in Mapbox.
Objective:
I have numerous locations with amounts ($) attached to each location. I want to use a polygon draw tool to draw a polygon around these locations that will automatically sum up the values ($) inside the polygon drawn and display it in a box on the top left corner of the map.
The Problem:
(1) I already have the polygon tool inserted in the map and have the box on the left of the map to display the sum of the amount ($) attached to each location but the number displayed is always wrong.
What I need now:
(1) Have the box on the left of the map display the sum of those locations accurately.
(2) When I drag the polygon across the map, the sum must change accordingly because the locations and therefore the amounts attached to those locations will be different.
I really need someone to help me edit my code. Yes, i have already visited numerous mapbox examples including the one where you can draw a polygon and it displays the area within it but i am unable to modify it to suit my needs.
My code:
const overlay = document.getElementById(‘map-overlay’);
map.addControl(draw);
map.on('draw.create',TotalSumALL);
map.on('draw.delete',TotalSumALL);
map.on('draw.update',TotalSumALL);
function TotalSumALL(e) {
const data = draw.getAll();
const answer = document.getElementById('map-overlay');
const features = map.queryRenderedFeatures({
layers: ['Locations']
});
if (features.length >= 10000) {
return window.alert('Select a smaller number of features');}
const names = features.map((feature) => feature.properties.InsuredName);
map.setFilter('Locations', ['in', 'InsuredName', ...names]);
// Total the Totals of all features.
const TotalSum = features.reduce((memo, feature) => {
if (typeof(feature.properties.Total) == 'string'){
let afterData = parseFloat(feature.properties.Total)
return afterData + memo
}
return memo + feature.properties.Total;
}, 0);
const Total = document.createElement('div');
Total.textContent =
'TIV: ' + TotalSum.toLocaleString();
overlay.innerHTML = '';
overlay.style.display = 'block';
overlay.appendChild(Total);
}
map.dragPan.enable();
});