Skip to content

Instantly share code, notes, and snippets.

@OpenSrcerer
Created March 23, 2022 19:00
Show Gist options
  • Save OpenSrcerer/81c1fc5a230c85a0c3c33b28d208161f to your computer and use it in GitHub Desktop.
Save OpenSrcerer/81c1fc5a230c85a0c3c33b28d208161f to your computer and use it in GitHub Desktop.
GeoJSON to Matrix Algorithm
/**
* Given a geoJson object, outputs a matrix with "0's" as open paths and "1's" as obstacles.
* @param geoJson Serialized GeoJson file to parse
* @param start Starting point for the path search
* @param end Ending point for the path
*/
function geoToMat(geoJson: Buffer, start: Point, end: Point): Double[][] {
var bbox = WhateverService.generateBbox(start, end);
var geoParsed: GeoJsonObject = GeoJsonParser.parse(geoJson); // parse serialized geojson into object
var geoBoxed: GeoJsonObject = drawBoundingBox(geoParsed, bbox); // Cut off the unrelated part (already did this)
var matrix: Double[][] = Matrix.ofSize(bbox.width, bbox.height, 0 /*starting value for cell*/); // Make a matrix with the size of the bbox
var polygons = geoBoxed.features.flatMap(multiPolygon => multiPolygon.getPolygons()); // Now you've got the independent polygons
polygons.forEach(poly => { // For each of the polygons
for (var i = 0; i < poly.coordinates.length; ++i) {
if (i === poly.coordinates.length - 1) {
drawLineBetweenTwoPoints(poly.coordinates[i], poly.coordinates[0]); // Draw line between first and last point
return;
}
drawLineBetweenTwoPoints(poly.coordinates[i], poly.coordinates[i + 1]); // Draw line between consecutive points
}
})
}
// DDA Algorithm for Graphics that I ported in this JS pseudocode
// https://en.wikipedia.org/wiki/Digital_differential_analyzer_(graphics_algorithm)
// THIS FUNCTION ASSUMES THAT MATRIX WAS PASSED BY REFERENCE
/**
* Draw a line on a given matrix given two points.
* @param matrix Matrix to draw line on.
* @param start Starting point.
* @param end Ending point.
*
* EXAMPLE, GIVEN MATRIX:
* 00000000000000
* 00000000000000
* 00000000000000
* 00000000000000
* 00000000000000
*
* AND POINTS:
* 10000000000000
* 00000000000000
* 00000000000000
* 00000000000000
* 00000000000001
*
* DRAWS: (do not take as exact output, algorithm is better than my example)
* 11000000000000
* 01111000000000
* 00001111100000
* 00000000111100
* 00000000000111
*/
function drawLineBetweenTwoPoints(matrix: Double[][], start: Point, end: Point) {
var point: Point = Point(0, 0);
var dx, dy, step;
dx = (x2 - x1); // Calculate the delta between x-s
dy = (y2 - y1); // Calculate the delta between y-s
step = (abs(dx) >= abs(dy)) ? abs(dx) : abs(dy); // See which way to go depending on function (x or y)
dx /= step; // "Alias" by step
dy /= step;
point.x = start.x; // Update temp point values
point.y = start.y;
var i = 1;
while (i <= step) {
matrix[x][y] = 1; // Mark position as "obstacle"
start.x += dx;
start.y += dy;
++i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment