0

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.

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);

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.