利用百度地图api解析地址的地理坐标

1、封装一个js文件

// bmpgl.js
export function BMPGL (ak) { // ak为百度地图api申请应用后获得
  return new Promise(function (resolve, reject) {
    window.init = function () {
      // eslint-disable-next-line
        resolve(BMapGL)
    }
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `http://api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=init`
    script.onerror = reject
    document.head.appendChild(script)
  })
}

2、在需要的页面引入js文件

import { BMPGL } from '@/assets/js/bmpgl'

 

3、封装为一个方法

    getGeo (location) { // 解析省份地理坐标
      console.log('解析省份地理坐标内部', location)
      return new Promise((resolve, reject) => {
        BMPGL(this.ak).then((BMapGL) => {
          const myGeo = new BMapGL.Geocoder()
          // eslint-disable-next-line no-unused-vars
          const p = null
          myGeo.getPoint(location, p => {
            if (p) {
              console.log('解析成功', p)
              resolve(p)
            } else {
              console.log('解析失败')
            }
          })
        }).catch(err => {
          console.log('errrrr', err)
          reject(err)
        })
      })
    }

 

4、方法的调用

 await that.getGeo('北京').then(res => {
   console.log('解析的地理坐标', res)
 })    

 

posted @ 2023-03-01 10:34  fnasklf  阅读(139)  评论(0编辑  收藏  举报