vue百度地图插件

1. 最终效果

百度地图

2. 申请百度地图秘钥

https://blog.csdn.net/weixin_42813606/article/details/88556804

3. 代码

(1)定义

地图组件:map.vue(重要的2个参数:中心点坐标和秘钥)

<template>
  <!-- 这是地图组价, 是一个公共的组件 -->
  <div
    :id="id"
    :style="{width:width+'px',height:height+'px',margin:'34px auto'}"
    class="m-map"/>
</template>

<script>
export default {
  props: {
    width: {
      type:Number,
      default:300
    },
    height: {
      type:Number,
      default:300
    },
    // 中心点
    point: {
      type:Array,
      default(){
        return [116.46,39.92] // 1.中心点坐标(百度可查任意城市坐标)
      }
    }
  },
  data() {
    return {
      id: `map`,
      key: 'c577ac0dd939b69f706e6468330cdb85' // 2. 秘钥
    }
  },
  watch: {
    // 中心点 和  漂浮物
    point: function (val, old) {
      this.map.setCenter(val)
      this.marker.setPosition(val)
    }
  },
  mounted() {
    let self = this
    self.id = `map${Math.random().toString().slice(4, 6)}`

    window.onmaploaded = () => {
      let map = new window.AMap.Map(self.id, {
        resizeEnable: true,
        zoom: 11, // 默认缩放级别,越大越详细
        center: self.point
      })
      self.map = map
      //
      window.AMap.plugin('AMap.ToolBar', () => {
        let toolbar = new window.AMap.ToolBar()
        map.addControl(toolbar)
        let marker = new window.AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position: self.point
        })
        self.marker = marker
        marker.setMap(map)
      })
    }
    const url = `https://webapi.amap.com/maps?v=1.4.10&key=${self.key}&callback=onmaploaded`
    let jsapi = document.createElement('script')
    jsapi.charset = 'utf-8'
    jsapi.src = url
    document.head.appendChild(jsapi)
  },
}
</script>

(2)使用

<template>
  <div class="mt-products">
    <el-row>
      <el-col :span="19">
        <Crumbs/>
        <Category/>
        <List/>
      </el-col>
      <el-col :span="5">
        <Map
          v-if="point.length"
          :width="230"
          :height="290"
          :point="point"/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import Crumbs from '@/components/products/crumbs.vue'
  import Category from '@/components/products/category.vue'
  import List from '@/components/products/list.vue'
  import Map from '@/components/public/map.vue' // 1. 引入

  export default {
    components: {
      Crumbs,
      Category,
      List,
      Map
    },
    data () {
      return {
        point: [114.30, 30.60] // 2. 传入自定义中心点坐标
      }
    }
  }
</script>

<style lang="scss">
  @import '@/assets/css/products/products.scss';
</style>
发布了32 篇原创文章 · 获赞 0 · 访问量 994

猜你喜欢

转载自blog.csdn.net/weixin_42588966/article/details/103594300