text-to-map 1.1.19 → 1.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { readFileSync, writeFileSync } from "fs";
11
- import { getNewMunicipalityByName, parseOrdinanceToAddressPoints, } from "../street-markdown/smd";
11
+ import { parseOrdinanceToAddressPoints, } from "../street-markdown/smd";
12
+ import { municipalityToPolygons } from "../street-markdown/polygons";
13
+ import { disconnectKnex } from "../db/db";
12
14
  function main() {
13
15
  return __awaiter(this, void 0, void 0, function* () {
14
16
  // take first node argument as a file name
@@ -35,7 +37,7 @@ function main() {
35
37
  warningCount++;
36
38
  };
37
39
  console.time("downloadAndImportAllLatestAddressPoints");
38
- const { municipality } = yield getNewMunicipalityByName("Česká Lípa");
40
+ // const { municipality } = await getNewMunicipalityByName("Česká Lípa");
39
41
  const addressPoints = yield parseOrdinanceToAddressPoints({
40
42
  lines,
41
43
  initialState: {
@@ -46,6 +48,11 @@ function main() {
46
48
  includeUnmappedAddressPoints: true,
47
49
  });
48
50
  console.timeEnd("downloadAndImportAllLatestAddressPoints");
51
+ const polygons = [];
52
+ for (const municipality of addressPoints) {
53
+ polygons.push(yield municipalityToPolygons(municipality));
54
+ }
55
+ yield disconnectKnex();
49
56
  console.log(`Parsed ${lines.length} lines, ${errorCount} errors, ${warningCount} warnings.`);
50
57
  if (errorCount > 0) {
51
58
  console.log("Errors:");
@@ -60,6 +67,12 @@ function main() {
60
67
  else {
61
68
  console.log(JSON.stringify(addressPoints));
62
69
  }
70
+ if (process.argv.length >= 5) {
71
+ const outputFileName = process.argv[4];
72
+ const output = JSON.stringify(polygons);
73
+ console.log(`Writing polygons to ${outputFileName}`);
74
+ writeFileSync(outputFileName, output);
75
+ }
63
76
  });
64
77
  }
65
78
  main();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { readFileSync, writeFileSync } from "fs";
11
+ import { municipalityToPolygons } from "../street-markdown/polygons";
12
+ import { disconnectKnex } from "../db/db";
13
+ function main() {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ // take first node argument as a file name
16
+ if (process.argv.length < 3) {
17
+ console.error("Missing file name argument");
18
+ process.exit(1);
19
+ }
20
+ const fileName = process.argv[2];
21
+ const fileContent = readFileSync(fileName);
22
+ const json = JSON.parse(fileContent.toString());
23
+ const municipalityPolygons = yield municipalityToPolygons(json[0]);
24
+ yield disconnectKnex();
25
+ const output = JSON.stringify(municipalityPolygons);
26
+ if (process.argv.length >= 4) {
27
+ const outputFileName = process.argv[3];
28
+ console.log(`Writing polygons to ${outputFileName}`);
29
+ writeFileSync(outputFileName, output);
30
+ }
31
+ else {
32
+ console.log(JSON.stringify(output));
33
+ }
34
+ });
35
+ }
36
+ main();
@@ -1,2 +1,5 @@
1
+ import { FeatureCollection, MultiPolygon, Polygon } from "@turf/helpers";
1
2
  export declare const insertCityPositions: (data: string[][]) => Promise<number>;
2
3
  export declare const insertCities: (buffer: string[][]) => Promise<number>;
4
+ export declare const setCityPolygonGeojson: (polygon: FeatureCollection, code: string) => Promise<void>;
5
+ export declare const getCityPolygonGeojsons: (cityCodes: number[]) => Promise<Record<number, FeatureCollection<Polygon | MultiPolygon>>>;
package/dist/db/cities.js CHANGED
@@ -8,7 +8,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import chunk from "lodash/chunk";
11
- import { extractKeyValuesPairs, insertMultipleRows, rawQuery } from "./db";
11
+ import { extractKeyValuesPairs, getKnexDb, insertMultipleRows, rawQuery, } from "./db";
12
12
  const citiesColumn = {
13
13
  cityName: 0,
14
14
  cityCode: 1,
@@ -46,3 +46,19 @@ export const insertCities = (buffer) => __awaiter(void 0, void 0, void 0, functi
46
46
  citiesColumn.cityName,
47
47
  ]), "city", ["code", "name"]);
48
48
  });
49
+ export const setCityPolygonGeojson = (polygon, code) => __awaiter(void 0, void 0, void 0, function* () {
50
+ yield getKnexDb()
51
+ .from("city")
52
+ .update({ polygon_geojson: JSON.stringify(polygon) })
53
+ .where({ code });
54
+ });
55
+ export const getCityPolygonGeojsons = (cityCodes) => __awaiter(void 0, void 0, void 0, function* () {
56
+ const rows = yield getKnexDb()
57
+ .from("city")
58
+ .select("code", "polygon_geojson")
59
+ .whereIn("code", cityCodes);
60
+ return rows.reduce((acc, row) => {
61
+ acc[row.code] = JSON.parse(row.polygon_geojson);
62
+ return acc;
63
+ }, {});
64
+ });
@@ -284,11 +284,10 @@ export const getFounderCityCode = (founder) => __awaiter(void 0, void 0, void 0,
284
284
  if (founder.municipalityType === MunicipalityType.District) {
285
285
  if (cityCodeFounder !== founder) {
286
286
  cityCodeFounder = founder;
287
- cachedCityCode = yield getKnexDb()
288
- .pluck("city_code")
287
+ cachedCityCode = (yield getKnexDb()
289
288
  .from("city_district")
290
289
  .where("code", founder.cityOrDistrictCode)
291
- .first();
290
+ .first()).city_code;
292
291
  }
293
292
  return cachedCityCode;
294
293
  }
@@ -0,0 +1,23 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ export function up(knex) {
11
+ return __awaiter(this, void 0, void 0, function* () {
12
+ yield knex.schema.alterTable("city", (t) => {
13
+ t.text("polygon_geojson", "longtext").nullable();
14
+ });
15
+ });
16
+ }
17
+ export function down(knex) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ yield knex.schema.alterTable("city", (t) => {
20
+ t.dropColumn("polygon_geojson");
21
+ });
22
+ });
23
+ }
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { downloadAndImportAddressPoints } from "./open-data-sync/address-points"
3
3
  import { importCities } from "./open-data-sync/cities";
4
4
  import { downloadAndImportRegions } from "./open-data-sync/regions";
5
5
  import { downloadAndImportSchools } from "./open-data-sync/schools";
6
- import { downloadAndImportStreets } from "./open-data-sync/streets";
6
+ import { municipalityToPolygons } from "./street-markdown/polygons";
7
7
  import { OpenDataSyncOptionsPartial } from "./utils/helpers";
8
8
  export * from "./street-markdown/smd";
9
9
  export * from "./street-markdown/types";
@@ -19,4 +19,4 @@ export * from "./street-markdown/types";
19
19
  * ```
20
20
  */
21
21
  export declare function downloadAndImportEverything(options?: OpenDataSyncOptionsPartial, syncStreets?: boolean): Promise<void>;
22
- export { clearDb, downloadAndImportAddressPoints, downloadAndImportRegions, downloadAndImportSchools, downloadAndImportStreets, importCities, initDb, };
22
+ export { clearDb, downloadAndImportAddressPoints, downloadAndImportRegions, downloadAndImportSchools, importCities, municipalityToPolygons, initDb, };
package/dist/index.js CHANGED
@@ -12,7 +12,8 @@ import { downloadAndImportAddressPoints } from "./open-data-sync/address-points"
12
12
  import { importCities } from "./open-data-sync/cities";
13
13
  import { downloadAndImportRegions } from "./open-data-sync/regions";
14
14
  import { downloadAndImportSchools } from "./open-data-sync/schools";
15
- import { downloadAndImportStreets } from "./open-data-sync/streets";
15
+ // import { downloadAndImportStreets } from "./open-data-sync/streets";
16
+ import { municipalityToPolygons } from "./street-markdown/polygons";
16
17
  export * from "./street-markdown/smd";
17
18
  export * from "./street-markdown/types";
18
19
  /**
@@ -34,8 +35,10 @@ export function downloadAndImportEverything(options = {}, syncStreets = true) {
34
35
  yield downloadAndImportRegions(options);
35
36
  yield importCities(options);
36
37
  if (syncStreets) {
37
- yield downloadAndImportStreets(options);
38
+ // await downloadAndImportStreets(options);
38
39
  }
39
40
  });
40
41
  }
41
- export { clearDb, downloadAndImportAddressPoints, downloadAndImportRegions, downloadAndImportSchools, downloadAndImportStreets, importCities, initDb, };
42
+ export { clearDb, downloadAndImportAddressPoints, downloadAndImportRegions, downloadAndImportSchools,
43
+ // downloadAndImportStreets,
44
+ importCities, municipalityToPolygons, initDb, };
@@ -10,13 +10,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import { parse } from "csv-parse";
11
11
  import iconv from "iconv-lite";
12
12
  import { pipeline } from "stream/promises";
13
+ import { createReadStream } from "fs";
14
+ import { dirname, join } from "path";
15
+ import { fileURLToPath } from "url";
16
+ import { insertCityPositions } from "../db/cities";
13
17
  import { SyncPart } from "../db/types";
14
18
  import { prepareOptions, } from "../utils/helpers";
15
19
  import { runSyncPart } from "./common";
16
- import { createReadStream } from "fs";
17
- import { insertCityPositions } from "../db/cities";
18
- import { fileURLToPath } from "url";
19
- import { dirname, join } from "path";
20
20
  const importDataToDb = (options) => __awaiter(void 0, void 0, void 0, function* () {
21
21
  console.log("Starting to parse CSV file...");
22
22
  const __filename = fileURLToPath(import.meta.url);
@@ -11,6 +11,7 @@ import AdmZip from "adm-zip";
11
11
  import { createWriteStream, existsSync, mkdirSync, rmSync } from "fs";
12
12
  import fetch from "node-fetch";
13
13
  import parseDBF from "parsedbf";
14
+ import ShpToGeoJson from "shp-to-geojson";
14
15
  import { join } from "path";
15
16
  import { pipeline } from "stream/promises";
16
17
  import { deleteStreets, getAllSyncedStreets, insertStreetsFromDbf, setStreetAsSynced, } from "../db/street-sync";
@@ -18,6 +19,9 @@ import { SyncPart } from "../db/types";
18
19
  import { getAllUrlsFromAtomFeed, getLatestUrlFromAtomFeed, } from "../utils/atom";
19
20
  import { prepareOptions, } from "../utils/helpers";
20
21
  import { runSyncPart } from "./common";
22
+ import { coordEach } from "@turf/meta";
23
+ import jtsk2wgs84 from "../utils/jtsk2wgs84";
24
+ import { setCityPolygonGeojson } from "../db/cities";
21
25
  const prepareFolders = (options) => {
22
26
  const tempFolder = getTempFolder(options);
23
27
  if (!existsSync(tempFolder)) {
@@ -27,7 +31,7 @@ const prepareFolders = (options) => {
27
31
  const getTempFolder = (options) => {
28
32
  return join(options.tmpDir, options.streetZipFolderName);
29
33
  };
30
- const downloadZipAndParseDbfFile = (url, index, options) => __awaiter(void 0, void 0, void 0, function* () {
34
+ const downloadZipAndParseFiles = (url, index, options) => __awaiter(void 0, void 0, void 0, function* () {
31
35
  const response = yield fetch(url);
32
36
  if (response.status !== 200) {
33
37
  throw new Error(`The ZIP file from '${url}' could not be downloaded. HTTP Code: ${response.status}`);
@@ -36,16 +40,35 @@ const downloadZipAndParseDbfFile = (url, index, options) => __awaiter(void 0, vo
36
40
  yield pipeline(response.body, createWriteStream(zipFilePath));
37
41
  const zip = new AdmZip(zipFilePath);
38
42
  const folderName = zip.getEntries()[0].entryName;
43
+ const cityCode = folderName.substring(0, 6);
39
44
  const dbfEntryName = `${folderName}${options.streetDbfFileName}`;
40
- const obj = parseDBF(zip.getEntry(dbfEntryName).getData(), "win1250");
45
+ const streetData = parseDBF(zip.getEntry(dbfEntryName).getData(), "win1250");
46
+ const shpEntryName = `${folderName}${options.polygonShpFileName}`;
47
+ const polygonData = convertShpToGeoJson(zip.getEntry(shpEntryName).getData());
41
48
  rmSync(zipFilePath);
42
- return obj;
49
+ return { streetData, polygonData, cityCode };
43
50
  });
44
- const importDataToDb = (data) => __awaiter(void 0, void 0, void 0, function* () {
45
- if (data.length === 0) {
46
- return;
51
+ const convertShpToGeoJson = (shpBuffer) => {
52
+ const shp = new ShpToGeoJson({
53
+ arraybuffers: {
54
+ shpBuffer,
55
+ },
56
+ });
57
+ const geoJson = shp.getGeoJson();
58
+ delete geoJson.bbox;
59
+ coordEach(geoJson, (currentCoord) => {
60
+ const [y, x] = currentCoord;
61
+ const { lat, lon } = jtsk2wgs84(-x, -y);
62
+ currentCoord[0] = lon;
63
+ currentCoord[1] = lat;
64
+ });
65
+ return geoJson;
66
+ };
67
+ const importDataToDb = ({ streetData, polygonData, cityCode, }) => __awaiter(void 0, void 0, void 0, function* () {
68
+ if (streetData.length > 0) {
69
+ yield insertStreetsFromDbf(streetData);
47
70
  }
48
- yield insertStreetsFromDbf(data);
71
+ yield setCityPolygonGeojson(polygonData, cityCode);
49
72
  });
50
73
  const attempts = 5;
51
74
  export const downloadAndImportStreets = (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
@@ -75,8 +98,8 @@ export const downloadAndImportStreets = (options = {}) => __awaiter(void 0, void
75
98
  for (let i = 0; i < attempts; i++) {
76
99
  try {
77
100
  const zipLink = yield getLatestUrlFromAtomFeed(link);
78
- const dbfObject = yield downloadZipAndParseDbfFile(zipLink, done, completeOptions);
79
- yield importDataToDb(dbfObject);
101
+ const data = yield downloadZipAndParseFiles(zipLink, done, completeOptions);
102
+ yield importDataToDb(data);
80
103
  yield setStreetAsSynced(link);
81
104
  done++;
82
105
  console.log(`Loaded links: ${done}/${allDatasetFeedLinks.length}`);