2022年實時最新省市區縣鄉鎮街道geojson行政邊界數據獲取方法

geojson 數據下載地址://hxkj.vip/demo/echartsMap/

可下載的數據包含省級geojson行政邊界數據、市級geojson行政邊界數據、區/縣級geojson行政邊界數據、省市區縣街道行政編碼四級聯動數據(可精確到鄉鎮/街道級)

一、通過API接口,實時獲取最新中國省市區縣geoJSON格式地圖數據,可用於Echarts地圖展示

1、效果圖如下
在這裡插入圖片描述
在這裡插入圖片描述
2、示例代碼

 downloadMapCode() {// 下載mapCode數據
      let mapCode = [], cityMapCode = [], provinceMapCode = [], provinceList = [], cityList = [],
        districtList = [];
 
      provinceList = this.codeList.filter(item => {
        return item.level === 'province'
      })
      cityList = this.codeList.filter(item => {
        return item.level === 'city'
      })
      districtList = this.codeList.filter(item => {
        return item.level === 'district'
      })
 
      districtList.forEach(item => {
        mapCode.push({
          name: item.name,
          cityCode: item.code,
          fatherCode: `${item.code.substring(0, 4)}00`,
          children: []
        })
      })
 
      // 篩選出直轄市下面的區縣
      let direct = mapCode.filter(item => {
        return item.fatherCode.includes('0000');
      })
 
      for (let i in cityList) {
        let children = []
        for (let j in mapCode) {
          if (mapCode[j].fatherCode == cityList[i].code) {
            children.push(mapCode[j])
          }
        }
        cityMapCode.push({
          name: cityList[i].name,
          cityCode: cityList[i].code,
          fatherCode: `${cityList[i].code.substring(0, 2)}0000`,
          children: children
        })
      }
      cityMapCode = cityMapCode.concat(direct);
 
      for (let i in provinceList) {
        let children = []
        for (let j in cityMapCode) {
          if (cityMapCode[j].fatherCode == provinceList[i].code) {
            children.push(cityMapCode[j])
          }
        }
        provinceMapCode.push({
          name: provinceList[i].name,
          cityCode: provinceList[i].code,
          fatherCode: '100000',
          children: children
        })
      }
 
      if (provinceMapCode.length === 0) return
      this.zip.file(`mapCode.json`, JSON.stringify(provinceMapCode));
      this.downloadTips = '文件打包壓縮中...';
      this.zip.generateAsync({ type: "blob" })
        .then((content) => {
          saveAs(content, "mapCode.zip");
        });
    },
    // 下載全國地名和編碼(不包含邊界數據)
    downloadNameAndCode() {
      let opts = {
        subdistrict: 3, //返回下一級行政區
        showbiz: false, //最後一級返回街道信息
      };
      let district = new AMap.DistrictSearch(opts); //注意:需要使用插件同步下發功能才能這樣直接使用
      district.search('中國', function (status, result) {
        if (status === 'complete') {
          getData(result.districtList[0]);
        }
      });
      let _this = this
      function getData(data) {
        let districtList = data.districtList;
 
        let blob = new Blob([JSON.stringify(districtList)], {
          type: 'text/plain;charset=utf-8',
        });
        let filename = '全國省市區縣街道和編碼(不包含邊界數據)';
        _this.$ba.trackEvent('echartsMap', '全國省市區縣街道和編碼(不包含邊界數據)下載', filename);
        saveAs(blob, `${filename}.json`); //filename
      }
    },
    echartsMapClick(params) {//地圖點擊事件
      this.$ba.trackEvent('echartsMap', '點擊地圖', `${params.data.name}-${params.data.cityCode}`);
      if (params.data.level == 'street') return;
      //清除地圖上所有覆蓋物
      for (var i = 0, l = this.polygons.length; i < l; i++) {
        this.polygons[i].setMap(null);
      }
      this.cityName = params.data.name;
      this.cityCode = params.data.cityCode;
      this.district.setLevel(params.data.level); //行政區級別
      this.district.setExtensions('all');
      //行政區查詢
      //按照adcode進行查詢可以保證數據返回的唯一性
      this.district.search(this.cityCode, (status, result) => {
        if (status === 'complete') {
          this.getData(result.districtList[0], params.data.level, this.cityCode);
        }
      });
    },
    loadMapData(areaCode) {
      AMapUI.loadUI(['geo/DistrictExplorer'], DistrictExplorer => {
 
        //創建一個實例
        var districtExplorer = window.districtExplorer = new DistrictExplorer({
          eventSupport: true, //打開事件支持
          map: this.map
        });
 
        districtExplorer.loadAreaNode(areaCode, (error, areaNode) => {
 
          if (error) {
            console.error(error);
            return;
          }
          let mapJson = {};
          mapJson.type = "FeatureCollection";
          mapJson.features = areaNode.getSubFeatures();
          this.loadMap(this.cityName, mapJson);
          this.geoJsonData = mapJson;
        });
      });
    },

二、通過獲取到的數據整理一系列聯動數據,實現了每天自動更新

1、效果圖
在這裡插入圖片描述
2、示例代碼

downloadJson(nameType) {//geo文件下載
      this.nameType = nameType
      if (nameType === 'area') {
        this.$ba.trackEvent('echartsMap', '文件下載', '下載級聯數據');
        this.$refs.dialog.show();
        return;
      }
      if (nameType === 'all') {
        this.$ba.trackEvent('echartsMap', '文件下載', '打包下載全部');
        this.$refs.dialog.show();
        return;
      }
      if (nameType === 'street') {
        this.$ba.trackEvent('echartsMap', '文件下載', '下載鄉鎮數據');
        this.$refs.streetDialog.show();
        return;
      }
      var blob = new Blob([JSON.stringify(this.geoJsonData)], { type: "text/plain;charset=utf-8" });
      let filename = this.cityName;
      if (nameType === 'code') {
        filename = this.cityCode;
      }
      this.$ba.trackEvent('echartsMap', '文件下載', filename);
      saveAs(blob, `${filename}.geoJson`);//filename
    },
    dialogConfirm() {
      if (this.nameType === 'area') {
        this.$refs.mapDataDialog.show();
      } else {
        this.downloadAllJson()
      }
    },
    downloadAllJson() {//一次打包下載所有的數據
      this.showTips();
      if (this.downloadTips != '下載geoJson數據') {
        return;
      }
      this.codeList = [];
 
      this.downloadTips = '獲取數據中...';
 
      //                this.district.setLevel('country'); //行政區級別
      this.district.setExtensions('all');
      console.log('開始遞歸循環獲取地區code..');
      this.loopSearch('中國');
 
    },
    loopSearch(code) {
      setTimeout(() => {
        this.district.search(code, (status, result) => {
          if (status == 'complete') {
            console.log(`${code}--獲取成功`)
            for (let i in result.districtList[0].districtList) {
              this.codeList.push({
                name: result.districtList[0].districtList[i].name,
                code: result.districtList[0].districtList[i].adcode,
                level: result.districtList[0].districtList[i].level
              })
              //這邊沒想出來怎麼判斷數據是否全部加載完畢了,只能採用這種死辦法
              //有更好解決方案的大佬,麻煩告訴我一下,郵箱[email protected]
              //或者直接Github提交PR,在此不勝感激
              if (this.codeList.length >= 428) {// 為 3718 時,獲取區縣數據,428 省市數據
                console.log('code獲取完成');
                this.isCodeListLoadComplete = true;
              }
              if (result.districtList[0].districtList[i].adcode && result.districtList[0].districtList[i].level != 'city' && result.districtList[0].districtList[i].level != 'district' && result.districtList[0].districtList[i].level != 'street') {
                this.loopSearch(result.districtList[0].districtList[i].adcode)
              }
            }
          } else {//第一遍查詢出錯,再次執行查詢
            console.log(`${code}--第一次獲取失敗,正在嘗試進行第二次獲取`)
            this.district.search(code, (status, result) => {
              if (status == 'complete') {
                console.log(`${code}--第二次獲取成功`)
                for (let i in result.districtList[0].districtList) {
                  this.codeList.push({
                    name: result.districtList[0].districtList[i].name,
                    code: result.districtList[0].districtList[i].adcode,
                    level: result.districtList[0].districtList[i].level
                  })
                  //這邊沒想出來怎麼判斷數據是否全部加載完畢了,只能採用這種死辦法
                  //有更好解決方案的大佬,麻煩告訴我一下,郵箱[email protected]
                  //或者直接Github提交PR,在此不勝感激
                  if (this.codeList.length >= 428) {
                    console.log('code獲取完成');
                    this.isCodeListLoadComplete = true;
                  }
                }
              } else {
                console.log(`${code}--第二次獲取失敗,請聯繫email:[email protected]`)
              }
            })
          }
        });
      }, 500)
    },
    loadAllGeoJson() {//通過codeList加載全部geoJson數據
      console.log('開始加載geoJson數據');
      AMapUI.loadUI(['geo/DistrictExplorer'], DistrictExplorer => {
 
        //創建一個實例
        var districtExplorer = window.districtExplorer = new DistrictExplorer({
          eventSupport: true, //打開事件支持
          map: this.map
        });
        let mapJson = {};
        for (let i in this.codeList) {
          setTimeout(() => {
            districtExplorer.loadAreaNode(this.codeList[i].code, (error, areaNode) => {
              if (error) {
                this.codeList[i].geo = 'error';
                console.log(`${this.codeList[i].name}--${this.codeList[i].code},geo 數據獲取失敗,高德地圖的鍋^_^`)
              } else {
                mapJson.type = "FeatureCollection";
                mapJson.features = areaNode && areaNode.getSubFeatures() || '';
                this.codeList[i].geo = mapJson;
                console.log(`${this.codeList[i].level}--${this.codeList[i].name}--${this.codeList[i].code},geo 數據獲取成功,馬上為你打包`)
              }
 
              if (this.codeList[i].level === 'province') {
                this.zip.file(`100000/${this.codeList[i].code}.geoJson`, JSON.stringify(mapJson));
              } else {
                this.zip.file(`100000/${this.codeList[i].code.substring(0, 2)}0000/${this.codeList[i].code}.geoJson`, JSON.stringify(mapJson));
              }
 
              if (this.codeList.every(item => item.geo)) {
                console.log('ziped');
                let readme = `\r\n
                                            項目源碼github地址://github.com/TangSY/echarts-map-demo (歡迎star)
                                            \r\n
                                            個人空間://www.hxkj.vip (歡迎閑逛)
                                            \r\n
                                             Email:[email protected]  (遇到問題可以反饋)
                                         `;
                this.zip.file(`readMe(sourceCode).txt`, readme);
                this.downloadTips = '文件打包壓縮中...';
                this.zip.generateAsync({ type: "blob" })
                  .then((content) => {
                    saveAs(content, "geoJson數據包.zip");
                    this.downloadTips = '下載geoJson數據';
                    this.isCodeListLoadComplete = false;
                    this.$ba.trackEvent('echartsMap', '文件下載', '打包下載成功');
                  });
              }
            });
          }, 100 * i)
        }
      });
    },