Vue:如何在地圖上添加自定義覆蓋物(點)

首發日期:2019-1-25git


如何在地圖上添加自定義覆蓋物(點)



此文重點是在地圖上標點,因此就省去引入百度地圖的步驟了。


先給一下最終的效果。
github


這個效果主要是利用百度地圖的「覆蓋物」來實現的。
因爲我作的這個要求顯示不一樣的顏色來表明不一樣的所屬者,因此就作的麻煩一點。api


若是你的需求不要求特別顯示,那麼可使用bm-marker
函數

代碼大體以下:字體

<baidu-map  class="bm-view"  ak="省略" :center="省略">
     <bm-marker v-for="item in 省略"  :key="item.省略" :position="{lng: item.longitude, lat: item.latitude}" ></bm-marker>
</baidu-map>
  • 上面的代碼中position裏面的值是經緯度。有了經緯度來可以標上點。
  • ak是你申請的百度api的key
  • center是城市中心




若是你但願使用特別的圖標來給標上所有點,那麼也可使用bm-marker,它裏面有一個icon屬性,icon裏面的圖片能夠用來標點:this

<baidu-map  class="bm-view"  ak="省略" :center="省略">
    <bm-marker v-for="item in 省略"  :key="item.省略" :position="{lng: item.longitude, lat: item.latitude}"  :icon="{url: 'https://www.cnblogs.com/images/cnblogs_com/progor/1390402/o_bike2.png', size: {width: 32, height: 32}}"></bm-marker>
</baidu-map>
  • icon中的url是圖片的url路徑。




若是你想要顯示多種覆蓋物,那麼你可使用overlay。(要封裝,由於封裝以後才能傳值進去指定顯示什麼覆蓋物)
簡單的overlay是這樣子的:
url

爲何能夠基於這個組件來封裝是由於這個組件有如下幾個好處:code

  1. 能夠定製文本內容
  2. 它自己是一個元素,而不是一個圖片,(上面的「打點物」都是圖片(小紅點不肯定是否是,多是一個字體圖標的東西)),由於是元素,因此咱們可以使用border,background,color等等樣式來處理這個元素。


需求實現步驟:
1.定義一個MyOverLay:component

<template>
  <bm-overlay
    ref="customOverlay"
    :class="{sample: true}"
    :style="pointColor"
    pane="labelPane"
    @draw="draw">
  </bm-overlay>
</template>

<script>
import { BmOverlay } from 'vue-baidu-map'
export default {
  props: ['text', 'position', 'color'], // 用來接受傳入的值,用來定製樣式
  components: {
    BmOverlay
  },
  watch: {
    position: {
      handler () {
        this.$refs.customOverlay.reload()  // 當位置發生變化時,從新渲染,內部會調用draw
      },
      deep: true
    }
  },
  data () {
    return {
      pointColor: ''
    }
  },
  mounted () {
    this.pointColor = this.color // 這裏我是用來獲取傳入的值來定義樣式的,可能有點多餘了,pointColor是組件中綁定的樣式,color是傳進來的樣式。【這樣就能夠根據傳入的樣式來顯示不一樣樣子的點了】
  },
  methods: {
    // 這是百度地圖的重繪函數,用於維持覆蓋物的位置(這裏的值貌似會影響拖拉時的偏移度)
    draw ({ el, BMap, map }) {
      const { lng, lat } = this.position
      const pixel = map.pointToOverlayPixel(new BMap.Point(lng, lat))
      el.style.left = pixel.x - 16 + 'px'
      el.style.top = pixel.y - 16 + 'px'
    }
  }
}
</script>

<style>
.sample {
  width: 32px;
  height: 32px;
  line-height: 32px;
  border-radius: 32px;
  background: rgba(0,0,0,0.5);
  overflow: hidden;
  box-shadow: 0 0 5px #000;
  color: #fff;
  text-align: center;
  position: absolute;
}
.sample.active {
  background: rgba(0,0,0,0.75);
  color: #fff;
}
</style>


2.使用MyOverLay,傳給它須要的值:

<baidu-map  class="bm-view"  ak="省略" :center="省略">
    <my-overlay
                v-for="item in 省略"  :key="item.省略" :position="{lng: item.longitude, lat: item.latitude}"
                :text="item.省略"
                :color='省略(這裏能夠處理一下從而給每個組件實例都傳入自定義的值)'
               >
              </my-overlay>
</baidu-map>

想了解更多,能夠查看Vue百度地圖api的官網:https://dafrok.github.io/vue-baidu-map/#/

相關文章
相關標籤/搜索