使用js下载地区json文件

1.从网站

免费下载实时更新的geoJson数据、行政区划边界数据、区划边界坐标集合__HashTang

下载 全国省市区县乡村名称和编码 的josn文件

2.从中搜索到所需要的省或市、区,新建json文件复制进去cqCityToStreet.json

3.脚本文件downGeoData.js

const fs = require('fs');
const https = require('https');
const path = require('path');

// 原始数据(替换为你的实际数据)
const data = require('./cqCityToStreet.json'); // 假设数据保存在这个文件中

// 配置参数
const OUTPUT_DIR = 'chongqing';
const BASE_URL = 'https://geo.datav.aliyun.com/areas_v3/bound';

async function main() {
  try {
    // 1. 创建输出目录
    const dirPath = path.join(__dirname, OUTPUT_DIR);
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath, { recursive: true });
      console.log(`目录创建成功: ${dirPath}`);
    }

    // 2. 保存原始数据文件
    const sourceFilePath = path.join(dirPath, 'cqCityToStreet.json');
    fs.writeFileSync(sourceFilePath, JSON.stringify(data, null, 2));
    console.log('原始数据文件已保存:', sourceFilePath);

    // 3. 收集所有6位行政区划代码
    const codes = collectCodes(data);
    console.log('需要下载的行政区数量:', codes.length);

    // 4. 下载所有边界数据
    for (const [index, code] of codes.entries()) {
      try {
        await downloadGeoJSON(code, dirPath);
        console.log(`[${index + 1}/${codes.length}] ${code} 下载完成`);
      } catch (err) {
        console.error(`[${index + 1}/${codes.length}] ${code} 下载失败:`, err.message);
      }
      await sleep(200); // 防止请求过快
    }

    console.log('所有操作已完成!');
  } catch (err) {
    console.error('程序运行出错:', err);
  }
}

// 工具函数:收集行政区划代码
function collectCodes(obj, codes = []) {
  if (obj.code && obj.code.length === 6) codes.push(obj.code);
  if (obj.children) obj.children.forEach(child => collectCodes(child, codes));
  return codes;
}

// 工具函数:下载单个GeoJSON
function downloadGeoJSON(code, dirPath) {
  return new Promise((resolve, reject) => {
    const url = `${BASE_URL}/${code}.json`;
    const filePath = path.join(dirPath, `${code}.json`);

    https.get(url, (res) => {
      if (res.statusCode !== 200) {
        return reject(new Error(`HTTP ${res.statusCode}`));
      }

      const chunks = [];
      res.on('data', chunk => chunks.push(chunk));
      res.on('end', () => {
        fs.writeFile(filePath, Buffer.concat(chunks), (err) => {
          err ? reject(err) : resolve();
        });
      });
    }).on('error', reject);
  });
}

// 工具函数:延迟函数
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 启动程序
main();

使用js下载地区json文件_第1张图片

4.在common目录下打开cmd,运行命令node downGeoData.js

你可能感兴趣的:(javascript)