使用高德api實現對經緯度和地址的互換

需求:對用戶輸入的地址在高德地圖上進行定位顯示
運用技術棧:React+TS
請求方式:axios
操作平臺:Web

地址轉經緯度

1. 封裝

  /**
   * 將地址轉換爲經緯度
   * @param address : 地址
   * @base 高德api
   * @return: 經度和維度
   */
  addressToLocation = (address: any) => {
    return new Promise((resolve, reject) => {
    // 這個key是我個人的key用於作爲參數進行調用高德api等一系列高德操作 這裏只是拿我個人的作爲示範
    //你們可以自己去申請屬於自己的key,最好不用我得了, 如果你們不知道不知道如何申請key可以百度或者問我都可以
      const key = '70790502eb5fb33b2c8c031b8b65de82'
      const base = `http://restapi.amap.com/v3/geocode/geo?key=${key}&address=${address}`
      const err = '沒有匹配到地點'
      axios.get(base).then(({ data }) => {
        const { geocodes } = data
        const { location } = geocodes[0]
        const longitudeAndLatitude = location.split(',')
        if (data.info === 'OK') resolve({ code: 200, longitude: longitudeAndLatitude[0], latitude: longitudeAndLatitude[1] })
        else reject(err)
      })
    })
  }

2. 調用

this.addressToLocation(address).then((res) => {
  const { longitude, latitude } = res
  this.setState({
    markerPosition: { longitude, latitude } // 注意markerPosition即爲地圖上面顯示的點
  })
})

3. 定義基礎屬性和數據

constructor (props: SelectSiteProps) {
    super(props)
    this.mapPlugins = ['ToolBar']
    this.mapCenter = { longitude: 120, latitude: 35 }
    this.events = {
      created: (ins: any) => { console.log(ins) },
      // 點擊地圖上的點會觸發此函數此函數會攜帶你所點擊點的所有信息
      click: (e:any) => {
        const { lnglat: { lat, lng } } = e
        this.setState({ markerPosition: { longitude: lng, latitude: lat } })
      }
    }
    this.state = {
      markerPosition: { longitude: 121, latitude: 36 }
    }
  }

如果在React+TS中使用還需1添加類型定義(在constructor上面添加即可)

  tool: any
  mapPlugins: any[]
  mapCenter: { longitude: number; latitude: number }
  events: { created: (ins: any) => void; click: (e:any) => void }

屬性說明(附貼上高德官方地址更多屬性說明請移至此處https://elemefe.github.io/react-amap/components/map#


經緯度轉地址

addressToLocation = (location: any) => {
    return new Promise((resolve, reject) => {
      const key = '70790502eb5fb33b2c8c031b8b65de82'
      const base = `http://restapi.amap.com/v3/geocode/regeo?key=${key}&location=${location}`
      axios.get(base).then(({ data }) => {
        console.log(data) // data裏面會有轉換好的地區等信息
    })
  }

道理同以上地址轉經緯度一致 所以在此不過多說明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章