blob: e471aa1bbe38b4e89d7f133e9bc66d8e6998517c [file] [log] [blame]
Evan Siroky7891a6e2016-11-05 11:50:50 -07001var exec = require('child_process').exec
2var fs = require('fs')
evansirokyd401c892016-06-16 00:05:14 -07003
Evan Siroky477ece62017-08-01 07:08:51 -07004var area = require('@mapbox/geojson-area')
evansiroky70b35fe2018-04-01 21:06:36 -07005var geojsonhint = require('@mapbox/geojsonhint')
Evan Siroky8326cf02017-03-02 08:27:55 -08006var helpers = require('@turf/helpers')
Evan Siroky070bbb92017-03-07 23:48:29 -08007var multiPolygon = helpers.multiPolygon
Evan Siroky8326cf02017-03-02 08:27:55 -08008var polygon = helpers.polygon
Evan Siroky7891a6e2016-11-05 11:50:50 -07009var asynclib = require('async')
10var jsts = require('jsts')
Evan Sirokyb57a5b92016-11-07 10:22:34 -080011var rimraf = require('rimraf')
Evan Siroky7891a6e2016-11-05 11:50:50 -070012var overpass = require('query-overpass')
evansirokyd401c892016-06-16 00:05:14 -070013
Evan Siroky7891a6e2016-11-05 11:50:50 -070014var osmBoundarySources = require('./osmBoundarySources.json')
15var zoneCfg = require('./timezones.json')
Evan Siroky081648a2017-07-04 09:53:36 -070016
17// allow building of only a specified zones
18var filteredIndex = process.argv.indexOf('--filtered-zones')
19if (filteredIndex > -1 && process.argv[filteredIndex + 1]) {
20 filteredZones = process.argv[filteredIndex + 1].split(',')
21 var newZoneCfg = {}
22 filteredZones.forEach((zoneName) => {
23 newZoneCfg[zoneName] = zoneCfg[zoneName]
24 })
25 zoneCfg = newZoneCfg
26
27 // filter out unneccessary downloads
28 var newOsmBoundarySources = {}
29 Object.keys(zoneCfg).forEach((zoneName) => {
30 zoneCfg[zoneName].forEach((op) => {
31 if (op.source === 'overpass') {
32 newOsmBoundarySources[op.id] = osmBoundarySources[op.id]
33 }
34 })
35 })
36
37 osmBoundarySources = newOsmBoundarySources
38}
39
Evan Siroky7891a6e2016-11-05 11:50:50 -070040var geoJsonReader = new jsts.io.GeoJSONReader()
41var geoJsonWriter = new jsts.io.GeoJSONWriter()
Evan Siroky477ece62017-08-01 07:08:51 -070042var precisionModel = new jsts.geom.PrecisionModel(1000000)
43var precisionReducer = new jsts.precision.GeometryPrecisionReducer(precisionModel)
Evan Siroky7891a6e2016-11-05 11:50:50 -070044var distZones = {}
Evan Sirokyb57a5b92016-11-07 10:22:34 -080045var minRequestGap = 4
46var curRequestGap = 4
evansirokyd401c892016-06-16 00:05:14 -070047
Evan Siroky7891a6e2016-11-05 11:50:50 -070048var safeMkdir = function (dirname, callback) {
49 fs.mkdir(dirname, function (err) {
50 if (err && err.code === 'EEXIST') {
evansiroky4be1c7a2016-06-16 18:23:34 -070051 callback()
52 } else {
53 callback(err)
54 }
55 })
56}
57
Evan Sirokyb173fd42017-03-08 15:16:27 -080058var debugGeo = function (op, a, b, reducePrecision) {
evansirokybecb56e2016-07-06 12:42:35 -070059 var result
60
Evan Sirokyb173fd42017-03-08 15:16:27 -080061 if (reducePrecision) {
Evan Sirokyb173fd42017-03-08 15:16:27 -080062 a = precisionReducer.reduce(a)
63 b = precisionReducer.reduce(b)
64 }
65
evansiroky6f9d8f72016-06-21 16:27:54 -070066 try {
Evan Siroky7891a6e2016-11-05 11:50:50 -070067 switch (op) {
evansiroky6f9d8f72016-06-21 16:27:54 -070068 case 'union':
evansirokybecb56e2016-07-06 12:42:35 -070069 result = a.union(b)
evansiroky6f9d8f72016-06-21 16:27:54 -070070 break
71 case 'intersection':
evansirokybecb56e2016-07-06 12:42:35 -070072 result = a.intersection(b)
evansiroky6f9d8f72016-06-21 16:27:54 -070073 break
Evan Siroky070bbb92017-03-07 23:48:29 -080074 case 'intersects':
75 result = a.intersects(b)
76 break
evansiroky6f9d8f72016-06-21 16:27:54 -070077 case 'diff':
Evan Sirokyb173fd42017-03-08 15:16:27 -080078 result = a.difference(b)
evansiroky6f9d8f72016-06-21 16:27:54 -070079 break
80 default:
81 var err = new Error('invalid op: ' + op)
82 throw err
83 }
Evan Siroky7891a6e2016-11-05 11:50:50 -070084 } catch (e) {
Evan Sirokyb173fd42017-03-08 15:16:27 -080085 if (e.name === 'TopologyException') {
86 console.log('Encountered TopologyException, retry with GeometryPrecisionReducer')
87 return debugGeo(op, a, b, true)
88 }
evansiroky6f9d8f72016-06-21 16:27:54 -070089 console.log('op err')
evansirokybecb56e2016-07-06 12:42:35 -070090 console.log(e)
91 console.log(e.stack)
92 fs.writeFileSync('debug_' + op + '_a.json', JSON.stringify(geoJsonWriter.write(a)))
93 fs.writeFileSync('debug_' + op + '_b.json', JSON.stringify(geoJsonWriter.write(b)))
evansiroky6f9d8f72016-06-21 16:27:54 -070094 throw e
95 }
evansiroky6f9d8f72016-06-21 16:27:54 -070096
evansirokybecb56e2016-07-06 12:42:35 -070097 return result
evansiroky4be1c7a2016-06-16 18:23:34 -070098}
99
Evan Siroky070bbb92017-03-07 23:48:29 -0800100var fetchIfNeeded = function (file, superCallback, downloadCallback, fetchFn) {
101 // check for file that got downloaded
Evan Siroky7891a6e2016-11-05 11:50:50 -0700102 fs.stat(file, function (err) {
Evan Siroky070bbb92017-03-07 23:48:29 -0800103 if (!err) {
104 // file found, skip download steps
105 return superCallback()
106 }
107 // check for manual file that got fixed and needs validation
108 var fixedFile = file.replace('.json', '_fixed.json')
109 fs.stat(fixedFile, function (err) {
110 if (!err) {
111 // file found, return fixed file
112 return downloadCallback(null, require(fixedFile))
113 }
114 // no manual fixed file found, download from overpass
115 fetchFn()
116 })
evansiroky50216c62016-06-16 17:41:47 -0700117 })
118}
119
Evan Siroky7891a6e2016-11-05 11:50:50 -0700120var geoJsonToGeom = function (geoJson) {
Evan Siroky8326cf02017-03-02 08:27:55 -0800121 try {
122 return geoJsonReader.read(JSON.stringify(geoJson))
123 } catch (e) {
124 console.error('error converting geojson to geometry')
125 fs.writeFileSync('debug_geojson_read_error.json', JSON.stringify(geoJson))
126 throw e
127 }
Evan Siroky5669adc2016-07-07 17:25:31 -0700128}
129
Evan Siroky8b47abe2016-10-02 12:28:52 -0700130var geomToGeoJson = function (geom) {
131 return geoJsonWriter.write(geom)
132}
133
Evan Siroky7891a6e2016-11-05 11:50:50 -0700134var geomToGeoJsonString = function (geom) {
Evan Siroky5669adc2016-07-07 17:25:31 -0700135 return JSON.stringify(geoJsonWriter.write(geom))
136}
137
Evan Siroky7891a6e2016-11-05 11:50:50 -0700138var downloadOsmBoundary = function (boundaryId, boundaryCallback) {
139 var cfg = osmBoundarySources[boundaryId]
Evan Siroky1bcd4772017-10-14 23:47:21 -0700140 var query = '[out:json][timeout:60];('
141 if (cfg.way) {
142 query += 'way'
143 } else {
144 query += 'relation'
145 }
Evan Siroky7891a6e2016-11-05 11:50:50 -0700146 var boundaryFilename = './downloads/' + boundaryId + '.json'
147 var debug = 'getting data for ' + boundaryId
148 var queryKeys = Object.keys(cfg)
evansiroky63d35e12016-06-16 10:08:15 -0700149
Evan Siroky5669adc2016-07-07 17:25:31 -0700150 for (var i = queryKeys.length - 1; i >= 0; i--) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700151 var k = queryKeys[i]
Evan Siroky1bcd4772017-10-14 23:47:21 -0700152 if (k === 'way') continue
Evan Siroky7891a6e2016-11-05 11:50:50 -0700153 var v = cfg[k]
Evan Siroky5669adc2016-07-07 17:25:31 -0700154
155 query += '["' + k + '"="' + v + '"]'
evansiroky63d35e12016-06-16 10:08:15 -0700156 }
157
Evan Siroky5669adc2016-07-07 17:25:31 -0700158 query += ');out body;>;out meta qt;'
evansiroky4be1c7a2016-06-16 18:23:34 -0700159
evansiroky63d35e12016-06-16 10:08:15 -0700160 console.log(debug)
161
Evan Siroky7891a6e2016-11-05 11:50:50 -0700162 asynclib.auto({
163 downloadFromOverpass: function (cb) {
evansiroky50216c62016-06-16 17:41:47 -0700164 console.log('downloading from overpass')
Evan Siroky070bbb92017-03-07 23:48:29 -0800165 fetchIfNeeded(boundaryFilename, boundaryCallback, cb, function () {
Evan Sirokyb57a5b92016-11-07 10:22:34 -0800166 var overpassResponseHandler = function (err, data) {
167 if (err) {
168 console.log(err)
169 console.log('Increasing overpass request gap')
170 curRequestGap *= 2
171 makeQuery()
172 } else {
173 console.log('Success, decreasing overpass request gap')
174 curRequestGap = Math.max(minRequestGap, curRequestGap / 2)
175 cb(null, data)
176 }
177 }
178 var makeQuery = function () {
179 console.log('waiting ' + curRequestGap + ' seconds')
180 setTimeout(function () {
181 overpass(query, overpassResponseHandler, { flatProperties: true })
182 }, curRequestGap * 1000)
183 }
184 makeQuery()
evansiroky63d35e12016-06-16 10:08:15 -0700185 })
186 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700187 validateOverpassResult: ['downloadFromOverpass', function (results, cb) {
evansiroky63d35e12016-06-16 10:08:15 -0700188 var data = results.downloadFromOverpass
evansiroky70b35fe2018-04-01 21:06:36 -0700189 if (!data.features) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700190 var err = new Error('Invalid geojson for boundary: ' + boundaryId)
evansiroky63d35e12016-06-16 10:08:15 -0700191 return cb(err)
192 }
evansiroky70b35fe2018-04-01 21:06:36 -0700193 if (data.features.length === 0) {
194 console.error('No data for the following query:')
195 console.error(query)
196 console.error('To read more about this error, please visit https://git.io/vxKQL')
197 var err = new Error('No data found for from overpass query')
198 return cb(err)
199 }
evansiroky63d35e12016-06-16 10:08:15 -0700200 cb()
201 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700202 saveSingleMultiPolygon: ['validateOverpassResult', function (results, cb) {
203 var data = results.downloadFromOverpass
204 var combined
evansiroky63d35e12016-06-16 10:08:15 -0700205
206 // union all multi-polygons / polygons into one
207 for (var i = data.features.length - 1; i >= 0; i--) {
Evan Siroky5669adc2016-07-07 17:25:31 -0700208 var curOsmGeom = data.features[i].geometry
Evan Siroky7891a6e2016-11-05 11:50:50 -0700209 if (curOsmGeom.type === 'Polygon' || curOsmGeom.type === 'MultiPolygon') {
evansiroky63d35e12016-06-16 10:08:15 -0700210 console.log('combining border')
evansiroky70b35fe2018-04-01 21:06:36 -0700211 let errors = geojsonhint.hint(curOsmGeom)
212 if (errors && errors.length > 0) {
213 const stringifiedGeojson = JSON.stringify(curOsmGeom, null, 2)
214 errors = geojsonhint.hint(stringifiedGeojson)
215 console.error('Invalid geojson received in Overpass Result')
216 console.error('Overpass query: ' + query)
217 const problemFilename = boundaryId + '_convert_to_geom_error.json'
218 fs.writeFileSync(problemFilename, stringifiedGeojson)
219 console.error('saved problem file to ' + problemFilename)
220 console.error('To read more about this error, please visit https://git.io/vxKQq')
221 return cb(errors)
222 }
Evan Siroky070bbb92017-03-07 23:48:29 -0800223 try {
224 var curGeom = geoJsonToGeom(curOsmGeom)
225 } catch (e) {
226 console.error('error converting overpass result to geojson')
Evan Siroky477ece62017-08-01 07:08:51 -0700227 console.error(e)
evansiroky70b35fe2018-04-01 21:06:36 -0700228
Evan Siroky1bcd4772017-10-14 23:47:21 -0700229 fs.writeFileSync(boundaryId + '_convert_to_geom_error-all-features.json', JSON.stringify(data))
evansiroky70b35fe2018-04-01 21:06:36 -0700230 return cb(e)
Evan Siroky070bbb92017-03-07 23:48:29 -0800231 }
Evan Siroky7891a6e2016-11-05 11:50:50 -0700232 if (!combined) {
evansiroky63d35e12016-06-16 10:08:15 -0700233 combined = curGeom
234 } else {
Evan Siroky5669adc2016-07-07 17:25:31 -0700235 combined = debugGeo('union', curGeom, combined)
evansiroky63d35e12016-06-16 10:08:15 -0700236 }
237 }
238 }
Evan Siroky081c8e42017-05-29 14:53:52 -0700239 try {
240 fs.writeFile(boundaryFilename, geomToGeoJsonString(combined), cb)
241 } catch (e) {
242 console.error('error writing combined border to geojson')
243 fs.writeFileSync(boundaryId + '_combined_border_convert_to_geom_error.json', JSON.stringify(data))
evansiroky70b35fe2018-04-01 21:06:36 -0700244 return cb(e)
Evan Siroky081c8e42017-05-29 14:53:52 -0700245 }
evansiroky63d35e12016-06-16 10:08:15 -0700246 }]
247 }, boundaryCallback)
248}
evansirokyd401c892016-06-16 00:05:14 -0700249
Evan Siroky4fc596c2016-09-25 19:52:30 -0700250var getTzDistFilename = function (tzid) {
251 return './dist/' + tzid.replace(/\//g, '__') + '.json'
252}
253
254/**
255 * Get the geometry of the requested source data
256 *
257 * @return {Object} geom The geometry of the source
258 * @param {Object} source An object representing the data source
259 * must have `source` key and then either:
260 * - `id` if from a file
261 * - `id` if from a file
262 */
Evan Siroky7891a6e2016-11-05 11:50:50 -0700263var getDataSource = function (source) {
evansirokybecb56e2016-07-06 12:42:35 -0700264 var geoJson
Evan Siroky7891a6e2016-11-05 11:50:50 -0700265 if (source.source === 'overpass') {
evansirokybecb56e2016-07-06 12:42:35 -0700266 geoJson = require('./downloads/' + source.id + '.json')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700267 } else if (source.source === 'manual-polygon') {
evansirokybecb56e2016-07-06 12:42:35 -0700268 geoJson = polygon(source.data).geometry
Evan Siroky7891a6e2016-11-05 11:50:50 -0700269 } else if (source.source === 'manual-multipolygon') {
Evan Siroky8e30a2e2016-08-06 19:55:35 -0700270 geoJson = multiPolygon(source.data).geometry
Evan Siroky7891a6e2016-11-05 11:50:50 -0700271 } else if (source.source === 'dist') {
Evan Siroky4fc596c2016-09-25 19:52:30 -0700272 geoJson = require(getTzDistFilename(source.id))
evansiroky4be1c7a2016-06-16 18:23:34 -0700273 } else {
274 var err = new Error('unknown source: ' + source.source)
275 throw err
276 }
Evan Siroky5669adc2016-07-07 17:25:31 -0700277 return geoJsonToGeom(geoJson)
evansiroky4be1c7a2016-06-16 18:23:34 -0700278}
279
Evan Siroky477ece62017-08-01 07:08:51 -0700280/**
281 * Post process created timezone boundary.
282 * - remove small holes and exclaves
283 * - reduce geometry precision
284 *
285 * @param {Geometry} geom The jsts geometry of the timezone
evansiroky26325842018-04-03 14:10:42 -0700286 * @param {boolean} returnAsObject if true, return as object, otherwise return stringified
287 * @return {Object|String} geojson as object or stringified
Evan Siroky477ece62017-08-01 07:08:51 -0700288 */
evansiroky26325842018-04-03 14:10:42 -0700289var postProcessZone = function (geom, returnAsObject) {
Evan Siroky477ece62017-08-01 07:08:51 -0700290 // reduce precision of geometry
291 const geojson = geomToGeoJson(precisionReducer.reduce(geom))
292
293 // iterate through all polygons
294 const filteredPolygons = []
295 let allPolygons = geojson.coordinates
296 if (geojson.type === 'Polygon') {
297 allPolygons = [geojson.coordinates]
298 }
299
300 allPolygons.forEach((curPolygon, idx) => {
301 // remove any polygon with very small area
302 const polygonFeature = polygon(curPolygon)
303 const polygonArea = area.geometry(polygonFeature.geometry)
304
305 if (polygonArea < 1) return
306
307 // find all holes
308 const filteredLinearRings = []
309
310 curPolygon.forEach((curLinearRing, lrIdx) => {
311 if (lrIdx === 0) {
312 // always keep first linearRing
313 filteredLinearRings.push(curLinearRing)
314 } else {
315 const polygonFromLinearRing = polygon([curLinearRing])
316 const linearRingArea = area.geometry(polygonFromLinearRing.geometry)
317
318 // only include holes with relevant area
319 if (linearRingArea > 1) {
320 filteredLinearRings.push(curLinearRing)
321 }
322 }
323 })
324
325 filteredPolygons.push(filteredLinearRings)
326 })
327
328 // recompile to geojson string
329 const newGeojson = {
330 type: geojson.type
331 }
332
333 if (geojson.type === 'Polygon') {
334 newGeojson.coordinates = filteredPolygons[0]
335 } else {
336 newGeojson.coordinates = filteredPolygons
337 }
338
evansiroky26325842018-04-03 14:10:42 -0700339 return returnAsObject ? newGeojson : JSON.stringify(newGeojson)
Evan Siroky477ece62017-08-01 07:08:51 -0700340}
341
Evan Siroky7891a6e2016-11-05 11:50:50 -0700342var makeTimezoneBoundary = function (tzid, callback) {
evansiroky35f64342016-06-16 22:17:04 -0700343 console.log('makeTimezoneBoundary for', tzid)
344
Evan Siroky7891a6e2016-11-05 11:50:50 -0700345 var ops = zoneCfg[tzid]
346 var geom
evansiroky4be1c7a2016-06-16 18:23:34 -0700347
Evan Siroky7891a6e2016-11-05 11:50:50 -0700348 asynclib.eachSeries(ops, function (task, cb) {
evansiroky4be1c7a2016-06-16 18:23:34 -0700349 var taskData = getDataSource(task)
evansiroky6f9d8f72016-06-21 16:27:54 -0700350 console.log('-', task.op, task.id)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700351 if (task.op === 'init') {
evansiroky4be1c7a2016-06-16 18:23:34 -0700352 geom = taskData
Evan Siroky7891a6e2016-11-05 11:50:50 -0700353 } else if (task.op === 'intersect') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700354 geom = debugGeo('intersection', geom, taskData)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700355 } else if (task.op === 'difference') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700356 geom = debugGeo('diff', geom, taskData)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700357 } else if (task.op === 'difference-reverse-order') {
Evan Siroky8ccaf0b2016-09-03 11:36:13 -0700358 geom = debugGeo('diff', taskData, geom)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700359 } else if (task.op === 'union') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700360 geom = debugGeo('union', geom, taskData)
Evan Siroky8ccaf0b2016-09-03 11:36:13 -0700361 } else {
362 var err = new Error('unknown op: ' + task.op)
363 return cb(err)
evansiroky4be1c7a2016-06-16 18:23:34 -0700364 }
evansiroky35f64342016-06-16 22:17:04 -0700365 cb()
Evan Siroky4fc596c2016-09-25 19:52:30 -0700366 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700367 function (err) {
368 if (err) { return callback(err) }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700369 fs.writeFile(getTzDistFilename(tzid),
Evan Siroky477ece62017-08-01 07:08:51 -0700370 postProcessZone(geom),
evansirokybecb56e2016-07-06 12:42:35 -0700371 callback)
evansiroky4be1c7a2016-06-16 18:23:34 -0700372 })
373}
374
Evan Siroky4fc596c2016-09-25 19:52:30 -0700375var loadDistZonesIntoMemory = function () {
376 console.log('load zones into memory')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700377 var zones = Object.keys(zoneCfg)
378 var tzid
Evan Siroky4fc596c2016-09-25 19:52:30 -0700379
380 for (var i = 0; i < zones.length; i++) {
381 tzid = zones[i]
382 distZones[tzid] = getDataSource({ source: 'dist', id: tzid })
383 }
384}
385
386var getDistZoneGeom = function (tzid) {
387 return distZones[tzid]
388}
389
390var validateTimezoneBoundaries = function () {
evansiroky26325842018-04-03 14:10:42 -0700391 console.log('do validation... this may take a few minutes')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700392 var allZonesOk = true
393 var zones = Object.keys(zoneCfg)
394 var compareTzid, tzid, zoneGeom
Evan Siroky4fc596c2016-09-25 19:52:30 -0700395
396 for (var i = 0; i < zones.length; i++) {
397 tzid = zones[i]
398 zoneGeom = getDistZoneGeom(tzid)
399
400 for (var j = i + 1; j < zones.length; j++) {
401 compareTzid = zones[j]
402
403 var compareZoneGeom = getDistZoneGeom(compareTzid)
Evan Siroky070bbb92017-03-07 23:48:29 -0800404
405 var intersects = false
406 try {
407 intersects = debugGeo('intersects', zoneGeom, compareZoneGeom)
408 } catch (e) {
409 console.warn('warning, encountered intersection error with zone ' + tzid + ' and ' + compareTzid)
410 }
411 if (intersects) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700412 var intersectedGeom = debugGeo('intersection', zoneGeom, compareZoneGeom)
413 var intersectedArea = intersectedGeom.getArea()
Evan Siroky4fc596c2016-09-25 19:52:30 -0700414
Evan Siroky7891a6e2016-11-05 11:50:50 -0700415 if (intersectedArea > 0.0001) {
evansiroky70b35fe2018-04-01 21:06:36 -0700416 console.error('Validation error: ' + tzid + ' intersects ' + compareTzid + ' area: ' + intersectedArea)
417 const debugFilename = tzid.replace('/', '-') + '-' + compareTzid.replace('/', '-') + '-overlap.json'
418 fs.writeFileSync(
419 debugFilename,
420 JSON.stringify(geoJsonWriter.write(intersectedGeom))
421 )
422 console.error('wrote overlap area as file ' + debugFilename)
423 console.error('To read more about this error, please visit https://git.io/vx6nx')
Evan Siroky4fc596c2016-09-25 19:52:30 -0700424 allZonesOk = false
425 }
426 }
427 }
428 }
429
430 return allZonesOk ? null : 'Zone validation unsuccessful'
Evan Siroky4fc596c2016-09-25 19:52:30 -0700431}
432
evansiroky26325842018-04-03 14:10:42 -0700433let oceanZoneBoundaries
434
435var addOceans = function (callback) {
436 console.log('adding ocean boundaries')
437 const oceanZones = [
438 { tzid: 'Etc/GMT-12', left: 172.5, right: 180 },
439 { tzid: 'Etc/GMT-11', left: 157.5, right: 172.5 },
440 { tzid: 'Etc/GMT-10', left: 142.5, right: 157.5 },
441 { tzid: 'Etc/GMT-9', left: 127.5, right: 142.5 },
442 { tzid: 'Etc/GMT-8', left: 112.5, right: 127.5 },
443 { tzid: 'Etc/GMT-7', left: 97.5, right: 112.5 },
444 { tzid: 'Etc/GMT-6', left: 82.5, right: 97.5 },
445 { tzid: 'Etc/GMT-5', left: 67.5, right: 82.5 },
446 { tzid: 'Etc/GMT-4', left: 52.5, right: 67.5 },
447 { tzid: 'Etc/GMT-3', left: 37.5, right: 52.5 },
448 { tzid: 'Etc/GMT-2', left: 22.5, right: 37.5 },
449 { tzid: 'Etc/GMT-1', left: 7.5, right: 22.5 },
450 { tzid: 'Etc/GMT', left: -7.5, right: 7.5 },
451 { tzid: 'Etc/GMT+1', left: -22.5, right: -7.5 },
452 { tzid: 'Etc/GMT+2', left: -37.5, right: -22.5 },
453 { tzid: 'Etc/GMT+3', left: -52.5, right: -37.5 },
454 { tzid: 'Etc/GMT+4', left: -67.5, right: -52.5 },
455 { tzid: 'Etc/GMT+5', left: -82.5, right: -67.5 },
456 { tzid: 'Etc/GMT+6', left: -97.5, right: -82.5 },
457 { tzid: 'Etc/GMT+7', left: -112.5, right: -97.5 },
458 { tzid: 'Etc/GMT+8', left: -127.5, right: -112.5 },
459 { tzid: 'Etc/GMT+9', left: -142.5, right: -127.5 },
460 { tzid: 'Etc/GMT+10', left: -157.5, right: -142.5 },
461 { tzid: 'Etc/GMT+11', left: -172.5, right: -157.5 },
462 { tzid: 'Etc/GMT+12', left: -180, right: -172.5 }
463 ]
464
465 const zones = Object.keys(zoneCfg)
466
467 oceanZoneBoundaries = oceanZones.map(zone => {
468 console.log(zone.tzid)
469 const geoJson = polygon([[
470 [zone.left, 90],
471 [zone.left,-90],
472 [zone.right,-90],
473 [zone.right,90],
474 [zone.left, 90]
475 ]]).geometry
476
477 let geom = geoJsonToGeom(geoJson)
478
479 // diff against every zone
480 zones.forEach(distZone => {
481 geom = debugGeo('diff', geom, getDistZoneGeom(distZone))
482 })
483
484 return {
485 geom: postProcessZone(geom, true),
486 tzid: zone.tzid
487 }
488 })
489
490 callback()
491}
492
Evan Siroky7891a6e2016-11-05 11:50:50 -0700493var combineAndWriteZones = function (callback) {
Evan Siroky8b47abe2016-10-02 12:28:52 -0700494 var stream = fs.createWriteStream('./dist/combined.json')
evansiroky26325842018-04-03 14:10:42 -0700495 var streamWithOceans = fs.createWriteStream('./dist/combined-with-oceans.json')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700496 var zones = Object.keys(zoneCfg)
497
498 stream.write('{"type":"FeatureCollection","features":[')
evansiroky26325842018-04-03 14:10:42 -0700499 streamWithOceans.write('{"type":"FeatureCollection","features":[')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700500
501 for (var i = 0; i < zones.length; i++) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700502 if (i > 0) {
Evan Siroky8b47abe2016-10-02 12:28:52 -0700503 stream.write(',')
evansiroky26325842018-04-03 14:10:42 -0700504 streamWithOceans.write(',')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700505 }
506 var feature = {
507 type: 'Feature',
508 properties: { tzid: zones[i] },
509 geometry: geomToGeoJson(getDistZoneGeom(zones[i]))
510 }
evansiroky26325842018-04-03 14:10:42 -0700511 const stringified = JSON.stringify(feature)
512 stream.write(stringified)
513 streamWithOceans.write(stringified)
Evan Siroky8b47abe2016-10-02 12:28:52 -0700514 }
evansiroky26325842018-04-03 14:10:42 -0700515 oceanZoneBoundaries.forEach(boundary => {
516 streamWithOceans.write(',')
517 var feature = {
518 type: 'Feature',
519 properties: { tzid: boundary.tzid },
520 geometry: boundary.geom
521 }
522 streamWithOceans.write(JSON.stringify(feature))
523 })
524 asynclib.parallel([
525 cb => {
526 stream.end(']}', cb)
527 },
528 cb => {
529 streamWithOceans.end(']}', cb)
530 }
531 ], callback)
Evan Siroky8b47abe2016-10-02 12:28:52 -0700532}
533
Evan Siroky7891a6e2016-11-05 11:50:50 -0700534asynclib.auto({
535 makeDownloadsDir: function (cb) {
evansirokyd401c892016-06-16 00:05:14 -0700536 console.log('creating downloads dir')
evansiroky4be1c7a2016-06-16 18:23:34 -0700537 safeMkdir('./downloads', cb)
538 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700539 makeDistDir: function (cb) {
evansiroky4be1c7a2016-06-16 18:23:34 -0700540 console.log('createing dist dir')
541 safeMkdir('./dist', cb)
evansirokyd401c892016-06-16 00:05:14 -0700542 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700543 getOsmBoundaries: ['makeDownloadsDir', function (results, cb) {
evansirokyd401c892016-06-16 00:05:14 -0700544 console.log('downloading osm boundaries')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700545 asynclib.eachSeries(Object.keys(osmBoundarySources), downloadOsmBoundary, cb)
evansiroky63d35e12016-06-16 10:08:15 -0700546 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700547 createZones: ['makeDistDir', 'getOsmBoundaries', function (results, cb) {
evansiroky35f64342016-06-16 22:17:04 -0700548 console.log('createZones')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700549 asynclib.each(Object.keys(zoneCfg), makeTimezoneBoundary, cb)
evansiroky50216c62016-06-16 17:41:47 -0700550 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700551 validateZones: ['createZones', function (results, cb) {
Evan Siroky4fc596c2016-09-25 19:52:30 -0700552 console.log('validating zones')
553 loadDistZonesIntoMemory()
Evan Siroky081648a2017-07-04 09:53:36 -0700554 if (process.argv.indexOf('no-validation') > -1) {
555 console.warn('WARNING: Skipping validation!')
556 cb()
557 } else {
558 cb(validateTimezoneBoundaries())
559 }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700560 }],
evansiroky26325842018-04-03 14:10:42 -0700561 addOceans: ['validateZones', function (results, cb) {
562 addOceans(cb)
563 }],
564 mergeZones: ['addOceans', function (results, cb) {
Evan Siroky8b47abe2016-10-02 12:28:52 -0700565 console.log('merge zones')
566 combineAndWriteZones(cb)
567 }],
568 zipGeoJson: ['mergeZones', function (results, cb) {
569 console.log('zip geojson')
570 exec('zip dist/timezones.geojson.zip dist/combined.json', cb)
571 }],
evansiroky26325842018-04-03 14:10:42 -0700572 zipGeoJsonWithOceans: ['mergeZones', function (results, cb) {
573 console.log('zip geojson with oceans')
574 exec('zip dist/timezones-with-oceans.geojson.zip dist/combined-with-oceans.json', cb)
575 }],
Evan Siroky8b47abe2016-10-02 12:28:52 -0700576 makeShapefile: ['mergeZones', function (results, cb) {
577 console.log('convert from geojson to shapefile')
evansiroky26325842018-04-03 14:10:42 -0700578 rimraf.sync('dist/combined-shapefile.*')
579 exec(
580 'ogr2ogr -nlt MULTIPOLYGON dist/combined-shapefile.shp dist/combined.json OGRGeoJSON',
581 function (err, stdout, stderr) {
582 if (err) { return cb(err) }
583 exec('zip dist/timezones.shapefile.zip dist/combined-shapefile.*', cb)
584 }
585 )
586 }],
587 makeShapefileWithOceans: ['mergeZones', function (results, cb) {
588 console.log('convert from geojson with oceans to shapefile')
589 rimraf.sync('dist/combined-shapefile-with-oceans.*')
590 exec(
591 'ogr2ogr -nlt MULTIPOLYGON dist/combined-shapefile-with-oceans.shp dist/combined-with-oceans.json OGRGeoJSON',
592 function (err, stdout, stderr) {
593 if (err) { return cb(err) }
594 exec('zip dist/timezones-with-oceans.shapefile.zip dist/combined-shapefile-with-oceans.*', cb)
595 }
596 )
evansirokyd401c892016-06-16 00:05:14 -0700597 }]
Evan Siroky7891a6e2016-11-05 11:50:50 -0700598}, function (err, results) {
evansirokyd401c892016-06-16 00:05:14 -0700599 console.log('done')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700600 if (err) {
evansirokyd401c892016-06-16 00:05:14 -0700601 console.log('error!', err)
602 return
603 }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700604})