通过js node拉取腾讯地图省市区县四级数据

根据腾讯地图apikey拿取腾讯地图数据
在这里插入图片描述
首先创建一个文件夹,在文件夹中创建下面js文件,然后在当前文件夹cmd打开小黑框,执行
node xxx.js
在这里插入图片描述

const apiUrl = 'https://apis.map.qq.com/ws/district/v1/getchildren';
const apiKey = '腾讯地图apiKey';


async function getDistrictData(id) {
    await sleep(210)  //只能一秒拉取5次数据
    let url
    if (id) {
        url = `${apiUrl}?id=${id}&key=${apiKey}`
    } else {
        url = `${apiUrl}?key=${apiKey}`
    }
    const response = await fetch(url);
    const data = await response.json();
    if (data.status == 0) {
        return data.result[0];
    } else {
        return []
    }
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}


//写入txt文件
async function saveToDatabase(dataInfo, parentId, grade, detailName) {
    //node环境下写入文件txt  文件为当前目录下文件
    const fs = require('fs')
    // const content = 'id,' + dataInfo.id + ',fullname,' + dataInfo.fullname + ',parentId,' + parentId + ',lat,' + dataInfo.location.lat + ',lng,' + dataInfo.location.lng + '\n';
    const content = dataInfo.id + ',' + parentId + ',' + grade + ',' + dataInfo.fullname + ',' + detailName + ',' + dataInfo.location.lat + ',' + dataInfo.location.lng + '\n'
    const opt = {
        flag: 'a', // a:追加写入;w:覆盖写入
    }
    console.log(content);
    fs.writeFile('region.txt', content, opt, (err) => {
        if (err) {
            console.error(err)
        }
    })
}


// 获取所有省份数据
async function getAllProvinces() {
    const provinces = await getDistrictData();
    for (const province of provinces) {
        await saveToDatabase(province, 0, 1, province.fullname);
        await getRegin(province, 1, province.fullname);
    }
}


//根据父节点拿子对象
async function getRegin(region, grade, name) {

    const cities = await getDistrictData(region.id);

    for (const city of cities) {
        await saveToDatabase(city, region.id, grade + 1, name + '-' + city.fullname);
        if (grade < 4) {
         await getRegin(city, grade + 1, name + '-' + city.fullname);
        }

    }
}



getAllProvinces()  //代码执行

最后,生成的.txt文件可修改后缀名为.csv,然后打开可另存为.xlsx格式,这样数据库可直接导入

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值