文档:https://lbs.amap.com/api/webservice/guide/api/district/#limit
API: https://restapi.amap.com/v3/config/district?subdistrict=4&key=申请的key
key: 注册后免费获取
浏览器端访问
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>行政区域数据</title>
</head>
<body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
var key = '***';
var subdistrict = 2; // 数据的层级: 2:省市; 3:省市区 ......
$.get(`https://restapi.amap.com/v3/config/district?subdistrict=${subdistrict}&key=${key}`,
function (data, textStatus, jqXHR) {
console.log(data);
}
);
</script>
</body>
</html>
使用node生成json文件,转换为自己所需的格式
const axios = require('axios');
const fs = require('fs');
const key = '***';
const subdistrict = 2; // 数据的层级: 2:省市; 3:省市区 ......
axios
.get(
`https://restapi.amap.com/v3/config/district?subdistrict=${subdistrict}&key=${key}`
)
.then(function (res) {
console.log(res.data);
if (res.status == 200) {
const data = customData(res.data.districts[0].districts);
const jsonStr = JSON.stringify(data, '', '\t');
fs.writeFile('area.json', jsonStr, function (err) {
if (err) {
return console.error(err);
}
console.log('数据写入成功!');
});
}
})
.catch(function (error) {
console.log(error);
});
function customData(arr) {
let array = [];
get(arr, array);
return array;
function get(districts, children) {
districts.forEach(item => {
children.push({
value: item.adcode,
label: item.name,
});
if (item.districts.length != 0) {
children[children.length - 1].children = [];
get(item.districts, children[children.length - 1].children);
}
});
}
}