Last active
January 22, 2016 18:47
-
-
Save kevin-peel/ede88997258e9c0f1eb8 to your computer and use it in GitHub Desktop.
Sums the values of multiple fields in a GeoJSON into a new field.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Functions for use with GeoJSONs */ | |
| /* | |
| Pass data like so: var newGeoJson = sumFields(inputFC, inputFields, outputField) | |
| Input FC can be a point, line, polygon. Use the variable name assigned to the GeoJSON, not the L.geoJson variable | |
| inputFields can be a single field or an array of fields, formatted like so: [value1, value2, ..., valueN] | |
| outputField is the name of the output field | |
| */ | |
| /* Sum Fields | |
| These two functions are used to sum multiple columns of data from one GeoJSON together. | |
| They are based on the Sum function of TurfJS but modified to handle data from only one dataset instead of 2. | |
| */ | |
| //sumFields - receives an input feature class, an array of input fields that will be summed, and the name of a field that will be added to the GeoJSON | |
| function sumFields(polyFC, inFields, outField) { | |
| var values = []; | |
| polyFC.features.forEach(function(poly) { | |
| values.length = 0; | |
| for (var i = 0; i < inFields.length; i++) { | |
| values.push(poly.properties[inFields[i]]); | |
| } | |
| poly.properties[outField] = sum(values); | |
| }); | |
| return polyFC; | |
| } | |
| //sum - receives an array of values from sumFields and adds them together, returning the numeric value back to sumFields. | |
| function sum(x) { | |
| var value = 0; | |
| for (var i = 0; i < x.length; i++) { | |
| value += x[i]; | |
| } | |
| return value; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment