Skip to content

Instantly share code, notes, and snippets.

@beyoung
Created May 16, 2023 03:37
Show Gist options
  • Select an option

  • Save beyoung/50b2a79adc017db9fec6fe7a8dfff024 to your computer and use it in GitHub Desktop.

Select an option

Save beyoung/50b2a79adc017db9fec6fe7a8dfff024 to your computer and use it in GitHub Desktop.

Revisions

  1. beyoung created this gist May 16, 2023.
    46 changes: 46 additions & 0 deletions world-grid.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    import * as fs from 'fs';
    import { polygon, featureCollection } from '@turf/helpers';
    import booleanIntersects from '@turf/boolean-intersects'

    const degrees = 6

    const featureArray = []

    // create a geojson feature collection using TurfJS
    var collection = featureCollection(featureArray)

    fs.readFile(`./ne_110m_land.geojson`, function (err, data) {
    if (err) {
    console.log(err)
    } else {
    let landFeature = featureCollection(JSON.parse(data))['features']['features']

    for (let lat = -90; lat <= 90; lat += degrees) {
    for (let lon = -180; lon <= 180 - degrees; lon += degrees) {
    const latNext = (lat + degrees) <= 90 ? lat + degrees : 90
    const lonNext = (lon + degrees) <= 180 ? lon + degrees : 180

    // create a geojson polygon feature using TurfJS
    const feature = polygon([[[lon, lat], [lonNext, lat], [lonNext, latNext], [lon, latNext], [lon, lat]]])
    var isContains = false
    for (const element of landFeature) {
    isContains = booleanIntersects(element, feature)
    if (isContains) {
    break
    }
    }

    if (isContains) {
    collection.features.push(feature)
    }

    }
    }
    fs.writeFile(`./${degrees}-world-grid.geojson`, JSON.stringify(collection), function (err) {
    if (err) {
    console.error(err)
    }
    })
    }
    })