简体   繁体   中英

Building geojson coordinate grid in JS

I'm trying to build a coordinate grid using geojson format. My JS knowledge is a little basic so I'm struggling on how to build the grid not just in the x direction but the y direction, so I end up with a square grid not just a x-axis line.

This is my code:

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

How do I turn this from an x-axis incrementing loop to both x and y axis so it builds a grid not just a line of coordinates?

What you're doing is boiling down to the fact that enclosing your coordinate values in parenthesis () is materially different that what is intended or expected as part of GeoJSON. Take the following example - in this instance, what you believe to be the x, y point 1, 2 evaluates to simply 2 in JavaScript:

 console.log((1, 2))

It's clear from the documentation on GeoJSON FeatureCollection that the values for "coordinates" of a Polygon are expressed as an Array of Arrays (both enclosed in square brackets):

var newFeature = {
  "type": "Feature",
  "properties": {},
  "geometry": {
    "type": "Polygon",
    "coordinates": [[i, i]]
  }
}
geojson['features'].push(newFeature);

It's not clear where you got the guidance to the contrary to use parenthesis to enclose your coordinate values. It's also not clear how a single point is meant to create a polygon in this instance, but I can't knock it if it meets your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM