您好呀,刚刚看了一下您的:“微信小程序在地图上标点 markers & 画圈显示范围 circles”的案例,我想请教您一个问题,就是我的那个范围圈我想标点在圈内的就显示,圈外的就隐藏,这个要怎么实现呢?
(这样写他没有效果,该怎么改呢?)
你可以在小程序的代码中使用if语句来判断一个标点是否在圈内。具体的实现方法如下:
在onLoad函数中,定义一个数组来保存标点的经纬度信息:
yaml
Copy code
this.data.markers = [{
id: 1,
latitude: 39.91488908,
longitude: 116.40387397,
title: 'Marker 1'
}, {
id: 2,
latitude: 39.90466885,
longitude: 116.40656117,
title: 'Marker 2'
}];
在onLoad函数中,定义一个圆圈的经纬度信息和半径:
yaml
Copy code
this.data.circles = [{
latitude: 39.909609,
longitude: 116.397228,
radius: 1000
}];
在onLoad函数中,使用MapContext的getRegion方法获取当前地图的可视区域,并计算出当前可视区域的左上角和右下角的经纬度坐标:
php
Copy code
wx.createMapContext('map').getRegion({
success: res => {
this.setData({
latitude1: res.northeast.latitude,
longitude1: res.southwest.longitude,
latitude2: res.southwest.latitude,
longitude2: res.northeast.longitude
});
}
});
在onLoad函数中,使用forEach函数遍历所有的标点,并根据标点的经纬度坐标和圆圈的半径计算出标点到圆心的距离,如果距离小于等于半径,则将该标点的show属性设置为true,否则设置为false:
kotlin
Copy code
this.data.markers.forEach(marker => {
let distance = this.getDistance(marker.latitude, marker.longitude, this.data.circles[0].latitude, this.data.circles[0].longitude);
if (distance <= this.data.circles[0].radius) {
marker.show = true;
} else {
marker.show = false;
}
});
在wxml文件中,使用wx:if指令来判断标点的show属性是否为true,如果是则显示该标点:
php
Copy code
<map id="map" latitude="{{latitude}}" longitude="{{longitude}}" scale="{{scale}}" markers="{{markers}}" circles="{{circles}}">
<cover-view class="marker" wx:for="{{markers}}" wx:if="{{show}}">
{{title}}
</cover-view>
</map>
其中,{{show}}表示标点的show属性是否为true。
通过以上步骤,就可以实现在圈内的标点显示,圈外的标点隐藏的功能了。