用微信小程序写1个在地图上面触摸拖动时带拖动范围框并输出范围框左上角和右下角的经纬度的demo
以下是一个使用微信小程序开发的范例,实现了在地图上面触摸拖动时带拖动范围框,并输出范围框左上角和右下角的经纬度。
- 在小程序的pages文件夹中新建一个名为map的文件夹,然后在map文件夹下新建map.wxml、map.wxss、map.js、map.json四个文件。
map.wxml:
<view class="container">
<map class="map" id="map" bindregionchange="bindRegionChange" bindtap="bindTap"></map>
<view class="box" style="left:{{boxLeft}}px; top:{{boxTop}}px; width:{{boxWidth}}px; height:{{boxHeight}}px;"></view>
<view class="text">左上角经纬度:{{leftTop}}</view>
<view class="text">右下角经纬度:{{rightBottom}}</view>
</view>
map.wxss:
.container {
width: 100%;
height: 100%;
}
.map {
width: 100%;
height: 100%;
}
.box {
position: absolute;
border: 2px solid red;
background-color: rgba(255, 0, 0, 0.2);
pointer-events: none;
}
.text {
margin-top: 10px;
font-size: 14px;
text-align: center;
}
map.js:
Page({
data: {
leftTop: '',
rightBottom: '',
boxLeft: 0,
boxTop: 0,
boxWidth: 0,
boxHeight: 0
},
bindRegionChange: function (event) {
const that = this;
const mapCtx = wx.createMapContext('map');
mapCtx.getRegion({
success: function (res) {
const southwest = res.southwest;
const northeast = res.northeast;
that.setData({
leftTop: `${southwest.latitude.toFixed(6)}, ${southwest.longitude.toFixed(6)}`,
rightBottom: `${northeast.latitude.toFixed(6)}, ${northeast.longitude.toFixed(6)}`
});
}
});
},
bindTap: function (event) {
const that = this;
const x = event.detail.x;
const y = event.detail.y;
wx.createSelectorQuery().select('.box').boundingClientRect(function (rect) {
that.setData({
boxLeft: x - rect.width / 2,
boxTop: y - rect.height / 2,
boxWidth: rect.width,
boxHeight: rect.height
});
}).exec();
}
});
map.json:
{
"navigationBarTitleText": "地图范围框"
}
- 在app.json中将map页面添加到pages数组中:
{
"pages": [
"pages/index/index",
"pages/map/map"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "WeChat",
"navigationBarTextStyle": "black"
}
}
- 运行小程序,进入map页面即可在地图上触摸拖动时显示拖动范围框,并输出范围框左上角和右下角的经纬度
原文地址: https://www.cveoy.top/t/topic/iUnx 著作权归作者所有。请勿转载和采集!