Calculate average of a field value
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-13-2024 02:44 AM
We are working on Crisis Map, where we map accurate location using latitude and longitude value.
In some of the records we don't have latitude and longitude value but we are trying to populate it by taking average value of the Impacted area.
We have a requirement to fetch latitude and longitude value by calculating centre point using average method. Example if you have Field :- impact area value as [[10,10],[10,11],[11,11]], then latitude and longitude can be filled as [10.3, 10.6]. How to write script to fetch value of impacted area.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-13-2024 04:22 AM
Hi @Mehar Naaz1 ,
You can use a business rule, that works on creation or updation. you can add additional condition when "impact_area" field changes.
Then you can parse the string into array, and loop through the array and store the average values and then set it in the longitude and latitude field.
I've added the script for this logic below, make sure to add the correct backend names for the fields.
var str = current.impact_area.toString(); //add correct backend name for impact area field
// Remove all square brackets
var cleanedStr = str.replace(/^\[+/, '').replace(/\]+$/, '');
// Add required brackets
cleanedStr = '[['+cleanedStr+']]';
var longi = 0;
var lati = 0;
//covert string to array
var arr = JSON.parse(cleanedStr);
for(var i=0;i<arr.length;i++){
longi += arr[i][0];
lati += arr[i][1];
}
var len = arr.length + 1;
longi = longi/len;
lati = lati/len;
current.longitude = longi; //add correct backend name for longitude field
current.latitude = lati; //add correct backend name for latitude field
current.update();
Thanks,
hope this helps you.
Mark this helpful and accept the solution if it proves to be helpful.