Skip to content
Advertisement

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.

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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement