创建web应用
设置应用
导出城市数据
function downloadFile(content,mimeTypeStr,fileName) {
var myBlob = new Blob([content], { type: mimeTypeStr })
var hrefUrl = URL.createObjectURL(myBlob)
var a = document.createElement("a")
a.setAttribute("href",hrefUrl)
a.setAttribute("download",fileName)
a.setAttribute("target","_blank")
let clickEvent = document.createEvent("MouseEvents");
clickEvent.initEvent("click", true, true);
a.dispatchEvent(clickEvent);
}
let City = function (key) {
this.id = 0;
this.list = [];
this.key = key;
/**
* 处理字段信息(可根据自己的需求处理成自己想要的格式)
* @param data 当前数据
* @param parentData 父级数据
* @param id 当前自增ID
* @param pid 父ID
* @rerturn Object
* */
this.cityInfo = function (data, parentData, id, pid) {
// province:省份(直辖市会在province显示)
// city:市(直辖市会在province显示)
// district:区县
// street:街道
var levels = {
province:1,
city:2,
district:3,
street:4,
}
return {
id:parseInt(id),
name:data.name,
pid:pid,
level: levels[data.level]
};
}
/**
* 根据字段排序
* @param field 字段
* @return mixed
* */
this.fieldSort = function (field){
return function(a,b){
var value1 = a[field];
var value2 = b[field];
return value1 - value2;
}
}
/**
* 获取接口数据列表
* @return void
* */
this.get = function (keywords = '中国', page = 1) {
let that = this
$.ajax({
url:'https://restapi.amap.com/v3/config/district?parameters',
type:"GET",
async:false,
data:{
key: that.key,
keywords: keywords,
subdistrict:3,
output:"JSON",
page:page
},
success: function (result) {
if(result.status == 1) {
that.list = result.districts[0].districts;
}
}
})
}
/**
* 格式化数据
* @param list 列表数据
* @param parentData 父级数据
* @param pid 父自增ID
* @retrurn array
* */
this.formatData=function (list, parentData = {} ,pid = 0) {
let result = [];
for (let tmp in list) {
this.id ++;
id = this.id;
result.push(this.cityInfo(list[tmp], parentData, id, pid))
if (list[tmp].districts.length > 0) {
result = result.concat(this.formatData(list[tmp].districts, list[tmp], id))
}
}
return result;
}
/**
* 将结果转成JSON
* @return stringg
* */
this.toJson = function () {
var list = this.list.sort(this.fieldSort('adcode'));
var result = this.formatData(list);
return JSON.stringify(result);
}
}
var tool = new City('通过高德地图申请的web服务key')
tool.get();
downloadFile(tool.toJson(), 'text/plain', 'city.json');