根据腾讯地图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格式,这样数据库可直接导入