获取城市信息

214 阅读1分钟
import Regions from 'chinese_regions'; // 需要引用的第三方库

/** 封装一个判断是否正确的城市编码 辅助函数 */

const judgeCityType = (applianceLocation) => {
    if (applianceLocation.length !== 6 || !/^[0-9]+.?[0-9]$/.test(applianceLocation)) throw new Error('对不起,需要您传递一个正确的城市编码');
    if (applianceLocation.slice(2, 4) === '00') {
        return '省';
    } else if (applianceLocation.slice(4, 6) === '00') {
        return '市'
    } else {
        return '区'
    }
}
/** 获取地理名称 */
export const getLocationName = (applianceLocation) => {
    let locationName = null;
    const locationType = judgeCityType(applianceLocation)
    switch (locationType) {
        case '省':
            locationName = Regions.province.filter(loca => loca.code === applianceLocation)
            break;
        case '市':
            locationName = Regions.city.filter(loca => loca.code === applianceLocation)
            break;
        default:
            locationName = Regions.county.filter(loca => loca.code === applianceLocation)
            break;
    };
    // console.log(locationName,locationType)
    return locationName[0]
}