webpack中 VUE使用百度地图获取地理位置

百度地图

1、index.html中引入 百度地图api

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=key"></script>

2、在webpack.base.conf.js里面 配置

module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
externals: {
"BMap": "BMap"
},
}

3、引入使用,一定记住需要在mounted钩子函数里面操作API 因为地图需要在所以的dom树加载完毕后才能操作

 import BMap from 'BMap'
  export default {
    data() {
      location: null
    },
    mounted() {
      let _this = this
      var geolocation = new BMap.Geolocation()
      geolocation.getCurrentPosition(function(r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          const myGeo = new BMap.Geocoder()
          myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), data => {
            if (data.addressComponents) {
              const result = data.addressComponents
              const location = {
                creditLongitude: r.point.lat, // 经度
                creditLatitude: r.point.lng, // 纬度
                creditProvince: result.province || '', // 省
                creditCity: result.city || '', // 市
                creditArea: result.district || '', // 区
                creditStreet: (result.street || '') + (result.streetNumber || '') // 街道
              }
              _this.location = location
            }
          })
        }
      })
    }
}