vue项目调用百度地图定位,判断当前位置是否在目标位置范围内

之前用vue做了一个百度地图定位功能,判断是否当前位置在目标位置范围内的小功能,类似这样:

 

 

直接上代码

百度地图定位,设置目标位置范围,判断当前位置到目标位置的距离,BDMap.vue


<template>
    <div v-show="IsShowPosition">
        <div id="mapDiv" @click="hidePosition" style="width: 100%;height: 110%;background-color: rgb(0 0 0 / 78%);position: absolute;top: 0; z-index: 10;"></div>
        <p id="allmap" style="width: 90%;height: 90%;position: absolute;margin: 5%;top: 0; z-index: 11;"></p>
    </div>
</template>

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=百度申请的key"></script>
<script>
    export default {
        name: 'mobileIndex',
        data() {
            return {
                address:'',
                lng:'',
                lat:'',
                s:'',
            };
        },
        props: {
            IsShowPosition: {
                type: Boolean,
                default: false
            },
            IsLoadData: {
                type: Boolean,
                default: false
            },
            ids:{
                type:Object
            }
        }, 
        watch:{
            IsShowPosition(val, oldVal){//普通的watch监听
                console.log("IsShowPosition: "+val, oldVal);
                if(this.IsShowPosition){
                    this.getLocation();
                }
            },
            IsLoadData(val, oldVal){//普通的watch监听
                console.log("IsLoadData: "+val, oldVal);
                if(this.IsLoadData){
                    this.getLocation();
                }
            }
        },
        methods:
        {
            hidePosition() {
                //this.IsShowPosition = false;
                this.$emit('closepop'); //通知父组件改变。
            },
            showBaiDuMap(lng, lat) {
                var _this = this;
                // 百度地图API功能
                //地图初始化
                var map = new BMap.Map("allmap");
                var point = new BMap.Point(lng, lat);
                map.centerAndZoom(point, 15);

                var marker = new BMap.Marker(point);  // 创建标注
                map.addOverlay(marker);              // 将标注添加到地图中
                var opts = {
                    width : 200,     // 信息窗口宽度
                    height: 100,     // 信息窗口高度
                    title : _this.ids["xmmc"] , // 信息窗口标题
                    message:_this.ids["xmmc"]
                }

                var infoWindow = new BMap.InfoWindow(_this.ids["xmaddress"], opts);  // 创建信息窗口对象 
                marker.addEventListener("click", function(){          
                    map.openInfoWindow(infoWindow, point); //开启信息窗口
                }); 

                // 创建圆
                var circle = new BMap.Circle(point, _this.ids["xmfw"] * 1000, {
                    strokeColor: 'blue',
                    strokeWeight: 2,
                    strokeOpacity: 0.5
                });
                map.addOverlay(circle); // 增加圆

                //设置定位按钮位置
                var opts = {anchor:BMAP_ANCHOR_BOTTOM_RIGHT}
                //将定位控件添加到地图上
                map.addControl(new BMap.GeolocationControl(opts));
                //设置缩放按钮位置及类型
                var ove = {
                    anchor: BMAP_ANCHOR_TOP_RIGHT,
                    type: BMAP_NAVIGATION_CONTROL_ZOOM
                };
                //添加缩放按钮
                map.addControl(new BMap.NavigationControl(ove));
            },
            // 经纬度转换成三角函数中度分表形式。
            rad(d) {
                return d * Math.PI / 180.0; 
            },
            // 根据经纬度计算距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
            getDistance(lat1, lng1, lat2, lng2,_this) {

                var radLat1 = _this.rad(lat1);
                var radLat2 = _this.rad(lat2);
                var a = radLat1 - radLat2;
                var b = _this.rad(lng1) - _this.rad(lng2);
                var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
                s = s * 6378.137; // EARTH_RADIUS;
                s = Math.round(s * 10000) / 10000; //输出为公里

                _this.ids["s"] = s;

                var distance = s;
                var distance_str = "";

                if (parseInt(distance) >= 1) {
                    distance_str = distance.toFixed(1) + "km";
                } else {
                    distance_str = distance * 1000 + "m";
                }
                //s=s.toFixed(4);
                console.info('lyj 距离是', s);
                console.info('lyj 距离是', distance_str);
                return distance_str;
            },
            getLocation() {
                let _this = this;
                let geolocation = new BMap.Geolocation();  // 创建百度地理位置实例,代替 navigator.geolocation
                geolocation.getCurrentPosition(function(e) {
                    if(this.getStatus() == BMAP_STATUS_SUCCESS){
                        // 百度 geolocation 的经纬度属性不同,此处是 point.lat 而不是 coords.latitude
                        // console.log(_this.lng, _this.lat);
                        let point = new BMap.Point(e.point.lng, e.point.lat);
                        let gc = new BMap.Geocoder();
                        gc.getLocation(point, function(rs){
                            _this.address = rs.address;
                            _this.lng = rs.point.lng;
                            _this.lat = rs.point.lat;
                            _this.ids["address"] = rs.address;

                            _this.getDistance(_this.lat,_this.lng,_this.ids["xmlat"],_this.ids["xmlng"],_this);
                            //_this.$layer.alert("当前位置距离项目:"+_this.ids["s"]+"km");
                            //this.$emit('updateAddress',_this.ids); 

                            _this.showBaiDuMap(_this.ids["xmlng"], _this.ids["xmlat"]);

                            //window.sessionStorage.setItem('address', address);  // 地址存入sessionStorage,再次进入页面就不需要再次请求位置了
                        });
                    } else {
                        console.log(this.getStatus());
                    }
                });
            },
            init(){
                //this.getLocation();
            }
        },
        mounted(){
            this.init();
        }
    }
</script>

 

 

把 BDMap.vue 作为一个组件来调用,调用代码如下:

<template>
    <div>

<van-field v-model="xmaddress" label="项目地址" @click="showPosition" disabled right-icon="location-o" />

        <edit :IsShowPosition="IsShowPosition" :IsLoadData="IsLoadData" :ids="ids" @closepop="closepop"></edit>
    </div>
</template>

<script>
    import edit from './BDMap';
    export default {
        name: 'mobileIndex',
        data() {
            return {
                xmaddress:",
                ids:{},
                IsShowPosition:false,
                IsLoadData:false,
            };
        },
        components:{
            edit
        },
        methods:
        {
            closepop() {
                this.IsShowPosition = false;
                console.log(this.ids["s"])
            },
            showPosition() {
                if(this.xmaddress){
                    console.log(this.ids["s"])
                    this.IsShowPosition = true;
                }           
            }
        },
        mounted(){
            this.init();
        }
    }
</script>

 

还需要在vue项目的首页引用百度地图api

 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Vue项目调用百度地图API实现根据经纬度判断某个点是否在淮安地区范围内,可以按照以下步骤: 1. 在Vue项目中安装百度地图JavaScript API的SDK,可以通过以下命令进行安装: ``` npm install bmap-js-sdk --save ``` 2. 在Vue组件中引入百度地图的JavaScript API,可以在`mounted`钩子函数中进行初始化: ``` mounted() { this.initMap(); }, methods: { initMap() { const AK = '申请的百度地图API Key'; const BMap = window.BMap; this.map = new BMap.Map('map-container'); this.map.centerAndZoom(new BMap.Point(119.015, 33.61), 12); // 设置中心点和缩放级别 this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放 this.map.addControl(new BMap.NavigationControl()); // 添加平移缩放控件 this.map.addControl(new BMap.ScaleControl()); // 添加比例尺控件 this.map.addControl(new BMap.OverviewMapControl()); // 添加缩略地图控件 this.geo = new BMap.Geocoder(); // 初始化地理编码器 } } ``` 3. 根据淮安地区的经纬度信息,使用百度地图的多边形覆盖物来绘制淮安地区的范围,代码如下: ``` const points = [ new BMap.Point(119.004, 33.559), new BMap.Point(119.004, 33.678), new BMap.Point(119.16, 33.678), new BMap.Point(119.16, 33.559) ]; const polygon = new BMap.Polygon(points, {strokeColor: '#f00', strokeWeight: 2, strokeOpacity: 0.8, fillColor: '#f00', fillOpacity: 0.2}); this.map.addOverlay(polygon); ``` 4. 在Vue组件中定义一个方法,该方法接收一个经纬度对象作为参数,判断该经纬度是否在淮安地区的范围内,代码如下: ``` checkLocation(point) { const polygon = this.map.getOverlays()[0]; // 获取多边形覆盖物 if (polygon.containsPoint(point)) { console.log('该点在淮安地区范围内'); } else { console.log('该点不在淮安地区范围内'); } } ``` 5. 在Vue组件中调用`checkLocation`方法,传入经纬度参数,判断该点是否在淮安地区范围内,代码如下: ``` // 获取经纬度信息 const point = new BMap.Point(119.015, 33.61); // 调用checkLocation方法判断该点是否在淮安地区范围内 this.checkLocation(point); ``` 以上就是在Vue项目调用百度地图API实现根据经纬度判断某个点是否在淮安地区范围内的步骤。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YuanlongWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值