1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| import axios from 'axios' import fs from 'fs'
interface eachData { NO: string CNname: string LDname: string Province: string Local: string } type AllJsonData = eachData[] interface BaiduResult { status: number result: { location: { lng: number lat: number } precise: number confidence: number comprehension: number level: string analys_level: string } } interface AllResult { NO: string lng: number lat: number comprehension: number }
const Sleep = (ms: number) => { return new Promise((resolve) => setTimeout(resolve, ms)) }
const jsonData: AllJsonData = require('./白芷样点数据-NSII.json')
class LocationRequest { constructor(AllJsonData: AllJsonData) { this.DataSet = AllJsonData }
private static BaiduAPIKey = 'baiduapikey' private static Url = 'https://api.map.baidu.com/geocoding/v3/' DataSet: AllJsonData
async GetLocationOnce(Local: string, Province: string): Promise<BaiduResult> { const { data } = await axios.get( LocationRequest.Url + '?output=json&ak=' + LocationRequest.BaiduAPIKey + '&address=' + Local + '&city=' + Province + '&extension_analys_level=1', ) return data as BaiduResult }
async GetAllLocation(): Promise<AllResult[]> { let allResult: AllResult[] = [] for (let i = 0; i < this.DataSet.length; i++) { if (this.DataSet[i].Province != '0未记录' && this.DataSet[i].Local != '0未记录') { try { const data = await this.GetLocationOnce(this.DataSet[i].Local, this.DataSet[i].Province) console.log( `${this.DataSet[i].NO}:经纬度为:${data.result.location.lat},${data.result.location.lng},可解析度为:${data.result.comprehension}`, ) allResult.push({ NO: this.DataSet[i].NO, lng: data.result.location.lng, lat: data.result.location.lat, comprehension: data.result.comprehension, }) } catch (error) { console.log(`${this.DataSet[i].NO}的经纬度获取失败!\n${error}`) allResult.push({ NO: this.DataSet[i].NO, lng: 0, lat: 0, comprehension: 0, }) } } else { console.log(`${this.DataSet[i].NO}未记录省市或区!`) allResult.push({ NO: this.DataSet[i].NO, lng: 0, lat: 0, comprehension: 0, }) } await Sleep(2000) } return allResult } }
async function main() { const data = await new LocationRequest(jsonData).GetAllLocation() try { fs.writeFileSync('./白芷样点经纬度.json', JSON.stringify(data)) console.log('写入成功!') } catch (error) { console.log(error) } }
main()
|