Vue项目使用百度地图——经纬度地图组件的封装及使用

1 前言

要在vue项目使用百度地图api,首先应做以下配置

(1)index.html

index.html添加script

 <script src="http://api.map.baidu.com/api?v=3.0&ak=你的百度地图秘钥(ak)&callback=bMapInit"></script>
(2)webpack.base.conf.js

webpack.base.conf.js添加externals配置,内容如下,与entry平级

  entry: {
    app: ['babel-polyfill', './src/main.js']
  },
  externals: {
    'BMap': 'BMap'
  },
(3)组件中引用
import BMap from 'BMap'

随后便可根据你所需的功能添加相应的地图api,并作出vue项目应有的更改即可。

2 应用举例

需求分析:点击按钮弹出地图,地图可搜索位置,可切换城市,搜索出来的位置需要在地图中定点,除了搜索外,可以通过拖动地图然后点击选择位置,选择出来的位置需要记录经纬度,传递到父组件。
实现:本例子不实现点击按钮弹出功能,这个比较简单,fixed定位写个弹框即可。

实现效果

地图组件:
这里写图片描述
父组件:
点击确定,父组件获取到经纬度(demo只作打印处理)。
这里写图片描述

demo地图组件源码
<template>
  <div class="map" v-show="visible">
    <div id="map-core"></div>
    <div class="search">
      <div id="r-result">
        <p>搜索定位:</p>
        <input type="text" id="suggestId" value="百度"/>
      </div>
      <div class="lng-lat">
        <div class="item">
          <p>当前经度:</p>
          <input type="text" v-model="location.lng"/>
        </div>
        <div class="item">
          <p>当前纬度:</p>
          <input type="text" v-model="location.lat"/>
        </div>
        <div class="item btn"><button @click="selectLocation">确定</button></div>
      </div>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import BMap from 'BMap'
export default {
  data () {
    return {
      location: {
        lng: '',
        lat: ''
      },
      map: {},
      ac: {}
    }
  },
  mounted () {
    this.setMap()
    this.setSearch()
  },
  methods: {
    // 初始化地图
    setMap () {
      this.map = new BMap.Map('map-core')
      this.map.centerAndZoom(new BMap.Point(113.275, 23.117), 10)
      // 地图缩放控件
      const topLeftControl = new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT})
      // 城市选择控件
      const cityListControl = new BMap.CityListControl({anchor: BMAP_ANCHOR_TOP_RIGHT})
      // 比例尺控件
      const topLeftNavigation = new BMap.NavigationControl()
      this.map.addControl(topLeftControl)
      this.map.addControl(topLeftNavigation)
      this.map.addControl(cityListControl)
      const _this = this
      // 鼠标缩放
      setTimeout(function () {
        _this.map.setZoom(11)
      }, 2000) // 2秒后放大到11级
      this.map.enableScrollWheelZoom(true)
      // 点击获取经纬度
      this.map.addEventListener('click', function (e) {
        _this.location.lng = parseFloat(e.point.lng).toFixed(3)
        _this.location.lat = parseFloat(e.point.lat).toFixed(3)
      })
    },
    // 根据经纬度绘制地图中的坐标点
    drawLocation () {
      if(this.location.lng !== "" && this.location.lat !== ""){
        this.map.clearOverlays()
        const new_point = new BMap.Point(this.location.lng, this.location.lat)
        const marker = new BMap.Marker(new_point)
        this.map.addOverlay(marker)
        this.map.panTo(new_point) 
      }
    },
    // 搜索位置功能实现
    setSearch () {
      const _this = this
      //建立一个自动完成的对象
      this.ac = new BMap.Autocomplete({"input" : "suggestId", "location" : _this.map})
      //鼠标放在下拉列表上的事件
      this.ac.addEventListener("onhighlight", function(e) {
        let str = ""
        let _value = e.fromitem.value
        let value = ""
        if (e.fromitem.index > -1) {
          value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business
        }
        value = ""
        if (e.toitem.index > -1) {
          _value = e.toitem.value
          value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business
        }
      })
      let myValue
      //鼠标点击下拉列表后的事件
      this.ac.addEventListener("onconfirm", function(e) {
      let _value = e.item.value
        myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business
        _this.setPlace(myValue)
      });
    },
    setPlace (myValue) {
      const _this = this
      //清除地图上所有覆盖物
      this.map.clearOverlays()
      //智能搜索
      this.local = new BMap.LocalSearch(_this.map, {
        onSearchComplete: _this.onSearchComplete
      });
      this.local.search(myValue);
    },
    onSearchComplete () {
      //获取第一个智能搜索的结果
      let pp = this.local.getResults().getPoi(0).point
      this.location.lng = parseFloat(pp.lng).toFixed(3)
      this.location.lat = parseFloat(pp.lat).toFixed(3)
      this.map.centerAndZoom(pp, 18)
      //添加标注
      this.map.addOverlay(new BMap.Marker(pp))
    },
    // 向父组件传递经纬度
    selectLocation () {
      this.$emit('selectLocation', this.location)
    }
  },
  watch: {
    'location': {
      handler () {
        this.drawLocation()
      },
      deep: true
    },
    visible () {
      console.log('ddd')
    }
  }
}
</script>

<style lang="less" scoped>
  .map {
    width: 100%;
    height: 100%;
    font-size: 14px;
    #map-core {
      width: 100%;
      height: 90%;
    }
    .search {
      display: flex;
      margin-top: 10px;
      height: 40px;
      #r-result {
        display: flex;
        height: 20px;
        line-height: 20px;
        p {
          height: 20px;
          padding-right: 10px;
        }
        input {
          width: 180px;
          height: 20px;
        }
      }
      .lng-lat {
        display: flex;
        .item {
          display: flex;
          padding-left: 10px;
          height: 20px;
          line-height: 20px;
          p {
            height: 20px;
            padding-right: 10px;
          }
          input {
            width: 100px;
            height: 20px;
          }
          button {
            color: #fff;
            height: 28px;
            width: 60px;
            background: #40B0FF;
            border: 1px solid #40B0FF;
            border-radius: 2px;
            &:hover {
              background: #10B0FF;
              border: 1px solid #10B0FF;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
</style>
地图父组件中使用方法
  <v-map @selectLocation="selectLocation"></v-map>

methods

    selectLocation (location) {
      console.log(location)
      console.log(parseFloat(location.lng))
      console.log(parseFloat(location.lat))
    }

解析请看代码中的注释,本例子旨在于举例vue项目使用百度地图的方法,仅注重js实现,css部分有情趣请自行改善,有错误欢迎指出。
友情链接:百度地图api官网:http://lbsyun.baidu.com/jsdemo.htm#lite_2_1

猜你喜欢

转载自blog.csdn.net/Fabulous1111/article/details/80918032