美文网首页
Vue中使用百度地图

Vue中使用百度地图

作者: O槑頭槑腦 | 来源:发表于2019-03-29 11:18 被阅读0次

1、申请百度地图ak

  • ak会在引入百度js的时候用到

2、引入百度地图js

  • 在public/index.html里面添加下面代码,注意把“你的ak”替换成你申请的ak
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=F5g7TtwB3sBzNS7AKWvtCQTtCqlxxtGw"></script>

3、配置webpack

  • 找到webpack.base.conf.js
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生命周期之前进行操作,会报错。

相关文章

网友评论

      本文标题:Vue中使用百度地图

      本文链接:https://www.haomeiwen.com/subject/fptlbqtx.html