vue-baidu-map 使用("踩坑")心得

    最近在用vue开发应用,要用到百度地图,之前用jquery有用过百度地图的JS SDK,基本功能都有实现过,但是到vue上就必须得自己封装插件了,当然晚上有的自己肯定是不想再去造轮子的,除非这轮子不合适,一搜果然与现成的,传送门在这:https://dafrok.github.io/vue-baidu-map/#/zh/index,点击进去就是使用文档,但是有很多坑,这里说一下,免得大家重复掉进去浪费时间。

1.为了你的页面流畅,建议还是局部引用,如下:

import { BaiduMap, BmScale, BmGeolocation } from 'vue-baidu-map'

当然我只用到了这些,所以就只引入这些,其他的要使用的可以对照文档引入使用

2.先看代码

<baidu-map :center="map_center" :zoom="map_zoom" @ready="map_handler" :double-click-zoom="false" @dragend="getMapCenter" class="baidu-map-view" ak="mapAK">
                                        <bm-scale anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-scale>
                                    </baidu-map>

你对地图进行事件处理,必须要在ready事件之后,否者取不到BMap对象的(mapAK是百度key)

3.map_handler方法会传入两个对象,使用过JS SDK的人应该知道,对,传入的参数就是对应的JS sdk里面的对象,直接拿来直接使用,虽然插件有提供标签,但是对应的属性和方法太少了,所以还是通过SDK提供的方法来调用比较好

/* BMap是百度地图的对象,直接new出来跟原始的百度地图API一样使用,map是地图对象,可以调用对应的地图方法,比如添加marker */
        map_handler({ BMap, map }) {
            console.log("map_handler")
            let _this = this
            this.BMap = BMap
            this.map = map
            this.map_zoom = 15
        }

来一个栗子

getCurlocation() { // 获取浏览器当前定位
            if (!this.BMap) return false
            let BMap = this.BMap
            let geolocation = new BMap.Geolocation()
            let _this = this
            geolocation.getCurrentPosition(function(r) {
                _this.map_center = r.point
                _this.shop_lng = r.point.lng
                _this.shop_lat = r.point.lat
            })
        }

4.还有个小问题就是,如果是经纬度的话,要传给百度地图查找坐标点的话,一定要使用百度地图的方法,如下:

let point = new BMap.Point(this.shop_lng, this.shop_lat)

不然会不生效,一定要记住!!!

其他的基本参照百度地图JS sdk的方法使用就可以了,大概就是这些。

猜你喜欢

转载自blog.csdn.net/playboyanta123/article/details/86514891