公司需要做一个自己产品的一个模块功能,即全国省市县的下钻(离线使用)。我参考了echart官网的省市下钻,并且对项目的目录进行构思及设计,最后对各省市的json文件进行分类管理。
在刚开始的时候是调用高德的api进行获取各省市的json信息,由于项目需要离线,我第一想到的就是将拿到的信息以json形式存成文件,然后对国省市的json文件管理,使用**$.getJSON**方法按需加载相应的文件展示。json资源是我自行下载管理的,当然你们可以去网上下载已经整理好的,可能格式就需要自己修整了。我这里目前做了广东的完整下钻,其他还在努力更新中。
先看图,没弄成gif:
各省市县Json文件按需下载
这里给个链接你们可以去网上自己下载(阿里云)
我自己是通过高德Api获取的Json,然后调用savaAs的方法生成json文件。
使用高德api需要引用高德的key,这种方式直接可以在线去调用查看,因为离线原因,所以得舍弃这个方法,去模拟数据实现。
部分代码展示
/*
* 默认显示全国
* @cityName 点击时候存储的城市名称
* @parentCode 点击时候存储的城市行政区code
* */
var cityName = ['全国'];
var parentCode = [100000];
/**
* 利用高德api获取行政区边界geoJson
* adcode 行政区code 编号
**/
getGeoJson(100000); //100000是全国的code
function getGeoJson(adcode) {
var map = new AMap.Map('map', {
resizeEnable: true,
center: [116.30946, 39.937629],
zoom: 3
});
AMapUI.loadUI(['geo/DistrictExplorer'], DistrictExplorer => {
var districtExplorer = (window.districtExplorer = new DistrictExplorer({
eventSupport: true, //打开事件支持
map: map
}))
districtExplorer.loadAreaNode(adcode, function (error, areaNode) {
if (error) {
console.error(error);
return;
}
let Json = areaNode.getSubFeatures()
if (Json.length > 0 && Json[0].properties.level == 'district') {
parentJson = Json;
}
//说明当前是区县
//这里还有个问题就是获取mapData数据,这里调用getMapData方法又会重新生成一次value值
//其实应该为之前的数据,不过这只是测试数据,用的随机数,实际项目肯定会调接口
else if (Json.length == 0) {
Json = parentJson.filter(item => {
if (item.properties.adcode == adcode) {
return item;
}
})
}
//去获取数据
getMapData(Json);
});
})
}
//获取数据,这里我们用随机数模拟数据
function getMapData(Json) {
if (Json[20]) {
//这里为了让海南省的字在海南上面,将一些群岛都去掉了。
Json[20].geometry.coordinates = Json[20].geometry.coordinates.slice(0, 1);
}
let mapData = Json.map(item => {
return ({
name: item.properties.name,
value: Math.random() * 1000,
level: item.properties.level,
cityCode: item.properties.adcode
})
});
//geoJson必须这种格式
mapJson.features = Json;
//去渲染echarts
downMaps(mapData, mapJson);
}
// 点击方法,下载所需地图模块json
function downLoadJson(mapJson) {
// 下载所需地图模块json
var blob = new Blob([JSON.stringify(mapJson)], {
type: "text/plain;charset=utf-8"
});
let filename = parentCode[parentCode.length - 1];
saveAs(blob, `${filename}.json`); //filename
}
项目中按需获取离线文件
/*
* 默认显示全国
* @cityName 点击时候存储的城市名称
* @parentCode 点击时候存储的城市行政区code
* @rootUrl 根目录路径
* @rootName 根路径名称
* @childCity 市模块路径
* @childDistrict 镇模块路径
* */
var cityName = ['全国'];
var parentCode = [100000];
let rootUrl = 'data/';
let rootName = [''];
//根据城市的行政区code 编号获取相应的json文件
function getJson(cityCode) {
let url = `${rootUrl}${rootName.join('')}${cityCode}.json`;
$.getJSON(url, function (areaJson, err) {
getMapData(areaJson);
}).fail(function () {
alert('小编正在努力开发中');
listPop();
});
}
完整代码获取
https://github.com/leifcao/MapUnder.git
建议用webstrom或者IDEA打开,请求本地文件可能会出现跨域。
此笔记仅仅为了记录自己在项目中所学到的知识,如果有问题,可以提出,我们可以共同探讨。