Vue中使用百度地图

2019-03-29  本文已影响0人  O槑頭槑腦

1、申请百度地图ak

2、引入百度地图js

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

3、配置webpack

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

4、在页面中调用

<template>
  <div id="map">
  </div>
</template>

<script>
import BMap from 'BMap'
export default {
    name: 'Map',
    data () {
        return {
        }
    },
    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 || '') // 街道
              }
              let signlocation = location.creditProvince+location.creditCity+location.creditArea+location.creditStreet
              console.log(signlocation)
              sessionStorage.setItem('location',signlocation)
            }
          })
        }
      })
    },
  }
</script>
<style scoped lang="stylus">
#map
  min-height 100vh
</style>

需要注意的是:

如果你在mounted生命周期之前进行操作,会报错。

上一篇下一篇

猜你喜欢

热点阅读