Last active
March 31, 2018 02:13
-
-
Save ralexrdz/fb817ba89ae140c85571472f8d349142 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const statesGeojsons = JSON.parse(fs.readFileSync('states.json', 'utf8')) | |
const municipalitiesGeojsons = JSON.parse(fs.readFileSync('municipalities.json', 'utf8')) | |
const MongoClient = require('mongodb').MongoClient | |
const cuid = require('cuid') | |
const turf = require('turf') | |
const centroid = require('@turf/centroid') | |
const turfBbox = require('@turf/bbox') | |
const URL_PREFIX = 'http://localhost:3000' | |
let codesMap = {} | |
function getCenter (geometry) { | |
let shape = geometry.type === 'Polygon' | |
? turf.polygon(geometry.coordinates) | |
: turf.multiPolygon(geometry.coordinates) | |
return centroid(shape).geometry.coordinates | |
} | |
let states = statesGeojsons.features.map(feature => { | |
let url = `${URL_PREFIX}/places/${cuid()}` | |
let name = feature.properties.state_name | |
codesMap[feature.properties.state_code] = url | |
let [longitude, latitude] = getCenter(feature.geometry) | |
let bbox = turfBbox(feature.geometry) | |
return { | |
_id: url, | |
type: 'Place', | |
name, | |
address: name, | |
latitude, | |
longitude, | |
bbox: { | |
west: bbox[0], | |
south: bbox[1], | |
east: bbox[2], | |
north: bbox[3] | |
}, | |
level: 'state' | |
} | |
}) | |
let municipalities = municipalitiesGeojsons.features.map(feature => { | |
let state = states.find(s => s._id === codesMap[feature.properties.state_code]) | |
let name = feature.properties.mun_name | |
let [longitude, latitude] = getCenter(feature.geometry) | |
let bbox = turfBbox(feature.geometry) | |
return { | |
_id: `${URL_PREFIX}/places/${cuid()}`, | |
type: 'Place', | |
name, | |
address: `${name}, ${state.name}`, | |
state: state._id, | |
latitude, | |
longitude, | |
bbox: { | |
west: bbox[0], | |
south: bbox[1], | |
east: bbox[2], | |
north: bbox[3] | |
}, | |
level: 'municipality' | |
} | |
}) | |
MongoClient.connect('mongodb://localhost:27017') | |
.then(client => { | |
client.db('vientos-fresh').collection('states').insert(states) | |
client.db('vientos-fresh').collection('municipalities').insert(municipalities) | |
client.close() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment