Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Building a coordinate grid using js

I’m trying to take a rectangle grid and divide it into equal size square grids and generate the coordinates in JavaScript json.

So far I’ve been able to plot coordinates so they fill up the first line, but I’m not sure how I can fill the whole rectangle (I.e extending down multiple lines, not just one).

I imagine it’s likely going to need a second loop inside the first but I’m having a hard time getting this to pull through into the json output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var geojson = {};
var xStart = -180;
var yStart = -90; // Start coodinatate on y-axis
var xEnd = 180; // End point on x-axis
var yEnd = 90; // End point on y-axis
var gridSize = 10; // Size of the grid increments

geojson['type'] = 'FeatureCollection';
geojson['features'] = [];

for (let i = xStart; i <= xEnd; i += gridSize) {
    var newFeature = {
        "type": "Feature",
        "properties": {
    },
        "geometry": {
            "type": "Polygon",
            "coordinates": [[i, i]]
        }
    }
    geojson['features'].push(newFeature);
}
console.log(geojson);

>Solution :

As you mentioned, just putting in another loop will get you the full mapping.

var geojson = {};
var xStart = -180;
var yStart = -90; // Start coodinatate on y-axis
var xEnd = 180; // End point on x-axis
var yEnd = 90; // End point on y-axis
var gridSize = 10; // Size of the grid increments

geojson['type'] = 'FeatureCollection';
geojson['features'] = [];

for (let i = xStart; i <= xEnd; i += gridSize) {
  for (let j = yStart; j <= yEnd; j += gridSize) {
    var newFeature = {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [i, j]
        ]
      }
    }
    geojson['features'].push(newFeature);
  }
}
console.log(geojson);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading