小记Vue2中百度地图的使用

近期项目需求相关地图限定使用百度地图,功能比较简单。为了防止忘记特此发帖帮助记忆一下。效果图如下:
在这里插入图片描述

接下来我将分步骤演示一下。
(1)引入地图

npm i vue-baidu-map --s

安装完依赖后在main.js中全局引入地图使用

//百度地图
import BaiduMap from 'vue-baidu-map'

Vue.use(BaiduMap, {
  /* 需要注册百度地图开发者来获取你的ak */
  ak: '你的ak'
})

(2) 实现过程
首先是在template中使用标签进行渲染

<template>
	<div class="map-container relative">
      <div class="status-bar">
        <div class="status-item" v-for="(item, index) in statusArr" :key="index">
          <img :src="item.icon" />
          {{ item.text }}
        </div>
      </div>
<!--      :map-style="mapStyle"-->
      <baidu-map class="map" :center="markerPoint" :scroll-wheel-zoom="true" :zoom="16" :mapClick="false" @ready="handler" >
        <bm-marker v-for="marker in deviceList" :icon="markerIcon(marker)" :key="marker.id" :position="{ lng: +marker.longitude, lat: +marker.latitude }" @mouseover="infoWindowOpen(marker)" @mouseout="infoWindowClose">
        </bm-marker>
        <bm-info-window :show="show" :offset="{width: -20, height: 10}" :position="{ lng: +marker.longitude, lat: +marker.latitude }">
          <div>
            <div class="info-title">详情</div>
            <div class="info-content">
              <div>回收机编号:<span>{{ marker.oid }}</span></div>
              <div>回收机名称:<span>{{ marker.name }}</span></div>
              <div>地址:<span>{{ marker.address }}</span></div>
              <div>负责人:<span>{{ marker.manager }}</span></div>
              <div>电话:<span>{{ marker.managerPhone }}</span></div>
            </div>
          </div>
        </bm-info-window>
      </baidu-map>
    </div>
</template>

接下来是js部分:

<script>
  import { getDeviceMap } from '@/api'
  import kuaiman from '../assets/imgs/kuaiman-icon.png'
  import weiman from '../assets/imgs/weiman-icon.png'
  import yiman from '../assets/imgs/yiman-icon.png'
  const styleJson = require('./mapStyle.json')
  export default {
    data() {
      return {
        statusArr: [
          {
            icon: weiman,
            text: '未满'
          },
          {
            icon: kuaiman,
            text: '快满'
          },
          {
            icon: yiman,
            text: '已满'
          }
        ],
        marker: {},
        deviceList: [],
        markerPoint:{ lng: 120.90102, lat: 31.986646 },
        show:false,
        // mapStyle: {    //自定义地图样式
        //   // styleJson
        // }
      }
    },
    created() {
      getDeviceMap({}).then((res) => {
        this.deviceList= res.data
      })
    },
    methods: {
      handler({BMap, map}) {
      },
      infoWindowClose () {
        this.show = false
      },
      infoWindowOpen (marker) {
        this.marker = Object.assign(marker)
        this.show = true
      },
      markerIcon(marker) {
        let img = marker.over == 2 ? kuaiman : marker.over == 1 ? yiman : weiman
        return { url: img,  size: { width: 28, height: 42 }}
      }
    }
  }
</script>

以及一些样式的修改:

<style lang="less" scoped>
  .map-container {
    width: 100%;
    height: calc(100vh - 124px);
    .map {
      width: 100%;
      height: 100%;
    }
  }
  /deep/ .info-title {
    color: #333;
    font-size: 16px;
    font-weight: 600;
    line-height: 48px;
    width: 100%;
    border-bottom: 1px solid #dedede;
    background: #fff;
    text-indent: 20px;
  }
  /deep/ .info-content {
    min-height: 120px;
    background: #fff;
    color: #333;
    font-size: 14px;
    padding: 20px;
    div {
      line-height: 2;
      color: #666;
      span {
        color: #333;
      }
    }
  }

  /deep/ .BMap_bottom {
      display: none;
    }
    /deep/ .BMap_pop {
      > div,
      > img:nth-child(10) {
        display: none;
        overflow: unset;
      }
      > div:nth-child(9) {
        display: block;
        overflow: unset;
        width: 340px !important;
      }
      > div:nth-child(8){
        /*display: block;*/
      }
      .BMap_top {
        display: none;
      }
      .BMap_center {
        background: transparent;
        border: none;
        position: sticky !important;
        height: 100%;
      }
    }

  /deep/ .BMap_bubble_content{
      background: rgba(0, 0, 0, .5);
      border-radius: 8px;
    }
  /deep/ .BMap_shadow {
    display: none;
  }
  .status-bar {
    position: absolute;
    display: flex;
    left: 20px;
    top: 10px;
    z-index: 99;
    width: 400px;
    justify-content: space-between;
    padding: 7px 20px;
    box-sizing: border-box;
    height: 44px;
    box-shadow: 0px 2px 3px 0px rgba(51, 51, 51, 0.22);
    border-radius: 4px;
    background: #fff;
    opacity: .8;
    .status-item {
      font-size: 14px;
      color: #010101;
      img {
        width: 18px;
        height: 30px;
        vertical-align: middle;
        margin-right: 6px;
      }
    }
  }
</style>

至此地图上显示markers就实现了。此外再记录一下在地图上点击地点获取具体的经纬度信息和位置信息的功能实现。代码如下:
在这里插入图片描述

<el-dialog title="定位设置" :visible.sync="mapVisible" width="60%" id="mapDialog" :close-on-click-modal="false">
      <div class="map-container">
        <baidu-map  class="map" :center="center" :zoom="zoom" @ready="handler"
                    :scroll-wheel-zoom="true"
                    @click="clickEvent"
                    :mapClick="false"
                    ak="ZzYlvuckB72Cto3IoxEFeN7SUBt4vh7F">
          <bm-navigation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-navigation>
          <el-input v-model="keyword" @focus="showSearch = true" size="mini" class="search-input" placeholder="请输入关键词"></el-input>
          <bm-local-search v-show="showSearch" class="search" :keyword="keyword" :auto-viewport="true" :location="center" @infohtmlset="handleSelect"></bm-local-search>
          <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
          <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"  :showAddressBar="true" :autoLocation="true" @locationSuccess="getLoctionSuccess" ></bm-geolocation>
          <bm-view :style="{width:'100%',height: this.clientHeight+'px',flex: 1,marginBottom:'-30px'}">
          </bm-view>
        </baidu-map>
      </div>
      <div class="demo-input-suffix" >
        <el-link :underline="false" type="info">经度:</el-link><el-input  class="lineinput"  style="width:120px" size="mini" v-model.number="locData.longitude"></el-input>
        <el-link :underline="false" type="info">维度:</el-link><el-input  class="lineinput"  style="width:120px" size="mini" v-model.number="locData.latitude"></el-input>
        <el-link :underline="false" type="info">地址:</el-link><el-input  class="lineinput"  style="width:200px" size="mini" v-model="locData.address"></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click.native="mapVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click.native="findlocation">保存</el-button>
      </div>
    </el-dialog>

js代码实现如下:

methods: {
	handleSelect(e) {
        this.locData.address = e.address
        this.locData.longitude = e.point.lng;
        this.locData.latitude = e.point.lat;
      },
      handler ({BMap, map}) {
      	// 自动获取当前设备位置并设置marker
        // let _this = this;	// 设置一个临时变量指向vue实例,因为在百度地图回调里使用this,指向的不是vue实例;
        // let geolocation = new BMap.Geolocation();
        // geolocation.getCurrentPosition(function(r){
        //   _this.center = {lng: r.longitude, lat: r.latitude};		// 设置center属性值
        //   _this.autoLocationPoint = {lng: r.longitude, lat: r.latitude};		// 自定义覆盖物
        //   _this.initLocation = true;
        // },{enableHighAccuracy: true})
        window.map = map;
        window.Bmap = BMap;
      },
       //定位成功回调
      getLoctionSuccess(point, AddressComponent, marker){
        map.clearOverlays();
        let Icon_0 = new BMap.Icon("icon/map_marker_check.png", new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 36)});
        let myMarker = new BMap.Marker(new BMap.Point(point.point.lng, point.point.lat),{icon: Icon_0});
        map.addOverlay(myMarker);
        this.locData.longitude = point.point.lng;
        this.locData.latitude = point.point.lat;
      },
      findlocation(){
        this.form.lngLat = String(this.locData.longitude) + ',' + String(this.locData.latitude)
        this.form.longitude = this.locData.longitude
        this.form.latitude = this.locData.latitude
        this.form.address = this.locData.address
        this.mapVisible = false
      },
      mapShow(){
        this.mapVisible = true
      },
      //点击地图监听
      clickEvent(e){
        this.keyword = ''
        this.showSearch = false
        map.clearOverlays();
        let Icon_0 = new BMap.Icon(makerIcon, new BMap.Size(32, 32), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 36)});
        let myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat),{icon: Icon_0});
        map.addOverlay(myMarker);
        //用所定位的经纬度查找所在地省市街道等信息
        let point = new BMap.Point(e.point.lng, e.point.lat);
        let gc = new BMap.Geocoder();
        let _this = this;
        gc.getLocation(point, function (rs) {
          _this.locData.address = rs.address;
        });
        this.locData.longitude = e.point.lng;
        this.locData.latitude = e.point.lat;
      },
}

以及页面上一些样式细节代码如下:

<style scoped lang="less">
  .search-input {
    width: 240px;
    position: absolute;
    right: 20px;
    top: 14px;
    z-index: 99;
  }
  .search {
    width: 239px;
    position: absolute;
    z-index: 99;
    top: 40px;
    right: 20px;
    max-height: 400px;
    overflow: scroll;
    background: #fff;
    /deep/ div {
      border: none !important;
    }
    /deep/ a {
      display: none !important;
    }
  }
  .map-container {
    height: 450px;
    .map {
      height: 100%;
      position: relative;
    }
  }
  /deep/ .BMap_cpyCtrl .BMap_noprint .anchorBL {
    display: none;
  }
  /deep/ .citylist_popup_main .city_content_top {
    border-bottom: none;
  }
  /deep/ .BMap_bubble_title {
    a {
      display: none !important;
    }
  }
</style>

至此在vue项目中百度地图的简单使用就实现完成了。新手发帖,内容空洞,多多包涵~
在此祝大家新年快乐!虎虎生威!

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Vue2中使用百度地图API,可以使用vue-baidu-map插件来实现。首先,在入口文件main.js中引入该插件,并传入你申请的百度地图API Key。引用 具体步骤如下: 1. 首先,在入口文件main.js中引入vue-baidu-map插件,并传入你申请的百度地图API Key。代码如下: ```javascript import Vue from 'vue' import BaiduMap from 'vue-baidu-map' Vue.use(BaiduMap, { ak: '你申请的key' }) ``` 2. 然后,在需要使用地图的组件中,可以通过在template中使用`<baidu-map>`标签来渲染地图,代码如下: ```html <template> <div> <baidu-map :center="center" :zoom="zoom"></baidu-map> </div> </template> ``` 其中,`:center`为地图的中心点坐标,`:zoom`为地图的缩放级别。 3. 在组件的script部分,定义`center`和`zoom`的值,以及其他地图相关的属性和方法,代码如下: ```javascript export default { data() { return { center: { // 地图中心点坐标 lng: 116.404, lat: 39.915 }, zoom: 13 // 地图缩放级别 } } } ``` 通过以上步骤,你就可以在Vue2中使用百度地图API了。记得替换代码中的`'你申请的key'`为你自己申请的百度地图API Key。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Vue2中百地图API的使用](https://blog.csdn.net/m0_70015578/article/details/127875241)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Vue2.0中使用百度地图API的方法](https://blog.csdn.net/weixin_52479225/article/details/126579928)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值