Created
October 21, 2022 13:57
-
-
Save loleg/dff866f9d3ba769f7280a204318b74ef to your computer and use it in GitHub Desktop.
A tiny library to load common GeoJSON formats in Processing
This file contains 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
// A function that helps plot various GeoJSON to the canvas. This does not | |
// cover every type and use case, but may be a useful reference. | |
// See also: https://mappa.js.org/ | |
function drawGeoJson(json_data, palette='white') { | |
// Iterate every feature | |
json_data.features.forEach((feature, ix) => { | |
// Make sure that we have a properly formatted file | |
if (typeof feature.geometry !== 'object' || | |
typeof feature.geometry.coordinates !== 'object') { | |
console.error("Not in GeoJSON format!") | |
console.log(feature); | |
return; | |
} | |
let coordinates = feature.geometry.coordinates; | |
// Set a single color, or pick the next in an array of colors | |
fill(typeof palette == 'string' ? palette : palette[ix % palette.length]) | |
coordinates.forEach((shapegroup) => { | |
if (feature.geometry.type == 'Polygon') { | |
drawShape(coordinates); | |
} else if (feature.geometry.type == 'MultiPolygon') { | |
coordinates.forEach((polygroup) => { | |
drawShape(polygroup); | |
}); | |
} else if (feature.geometry.type == 'Point') { | |
drawPoints(coordinates); | |
} else { | |
console.warn('Unknown geometry type:', feature.geometry); | |
} | |
}); // -coordinates | |
}); // -features | |
} // -drawGeoJson | |
// We will use this function to draw a polygon shape | |
function drawShape(shapegroup) { | |
shapegroup.forEach((shape) => { | |
beginShape(); | |
shape.forEach((coordinate) => { | |
// Calculate the projection | |
let pos = projection(coordinate); | |
if (pos[0] == NaN) { | |
console.warn("NaN in shape!") | |
return; | |
} | |
vertex(pos[0], pos[1]); | |
}); | |
endShape(); | |
}); // -shapegroup | |
} | |
// An example point drawer, which you can replace with your own | |
function drawPoints(pointgroup, color, label=false) { | |
pointgroupo.forEach((point) => { | |
noStroke(); | |
fill(color); | |
// Calculate screen pixels | |
let pos = projection(point); | |
if (pos[0] == NaN) { | |
console.warn("NaN in point!") | |
return; | |
} | |
// Draw a circle and optional label | |
circle(pos[0], pos[1], 3) | |
if (label) { | |
text(feature.properties.name, pos[0] + 3, pos[1] + 3); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment