中年危机程序猿的日常

记录实现前端切换城市区县的过程

2017-07-28  本文已影响13人  脱非入欧

概述

记录从统计局发布的数据到前端可用的地区筛选框所做的事情。

需求

实现

数据来源

最新县及县以上行政区划代码(截止2016年7月31日)

处理步骤

  1. 打印PDF,另存为txt。
  2. 使用代码对数据进行处理。
    a = `[txt文档内容]`;
    // 按照空格分隔
    b = a.split(" ").filter(val => val!=="");
    // 把区划代码和区划名称中多个空格替换成空格,再次移除空值
    b = b.map(val => val.replace(/\s+/g, " "));
    b = b.filter(val => val!==" ");
    // 移除无用的pdf信息
    b = b.filter(val => !(val.startsWith("http") || val.includes("/") || val==="Page" || val.startsWith("最") || val.includes("-")));
    // 移除末尾无用信息
    c = b.slice(0, 4047);
    c = c.map(v => v.trim());
    // 有空格开头的,还有因为空格被拆成两个值的
    d = c.map((v,i,a) => {
            if (v.match(/^\d+\s*.+$/g)) {
                    if (i < a.length - 1) {
                            if (!a[i+1].match(/^\d+\s*.+$/g)) {
                                    return (v + " " + a[i+1]).trim();
                            } else { return v.trim();}
                    }
        }
    })
    d = d.filter(v=>v!==null && v!==undefined);
    // XX区居然在区前有空格
    d = d.map(val=>val.replace(/\s/g, ""));
    // 最后得到一个数组
    JSON.stringify(d);
    // "["110000北京市","110100市辖区","110101东城区"..."]"
    

数据存储

将数据按照省区分,每个省,作为静态资源存储,懒加载。

class District { 

  prov = new Array(); 

  getProvList = async (code) => { 
    if (this.prov.length === 0) { 
      await this.initProv(code); 
    } 
    return this.prov; 
  }; 

  getCityList = async (code) => { 
    if (this.prov.length === 0) { 
      await this.initProv(code); 
    } 
    return this.prov.filter(v => v.includes('00') && !v.includes('0000') && !v.includes(code)); 
  }; 

  getDistList = async (code) => { 
    if (this.prov.length === 0) { 
      await this.initProv(code); 
    } 
    return this.prov.filter(v => v.startsWith(code.substring(0, 4)) && !v.includes(code)); 
  }; 

  initProv = async (code) => {   
    const distList = await import(`./${code.substring(0, 2)}0000.js`); 
    this.prov = distList.default; 
    return this.prov; 
  }; 

  isProvCode = (code) => { 
    return code.includes('0000'); 
  }; 

  isCityCode = (code) => { 
    return code.includes('00') && !code.includes('0000'); 
  }; 

  isDistCode = (code) => { 
    return !(code.includes('00') || code.includes('0000')); 
  } 
} 

export default District; 

食用一下。

const config = new District(); 
config.getCityList('110000').then(val => (console.log(val))); 

Q & A

上一篇下一篇

猜你喜欢

热点阅读