微信小程序地图拖动范围框及经纬度获取 Demo
以下是一个使用微信小程序开发的范例,实现了在地图上面触摸拖动时带拖动范围框,并输出范围框左上角和右下角的经纬度。
1. 在小程序的pages文件夹中新建一个名为map的文件夹,然后在map文件夹下新建map.wxml、map.wxss、map.js、map.json四个文件。
map.wxml:
```html
左上角经纬度:{{leftTop}}
右下角经纬度:{{rightBottom}}
```
map.wxss:
```css
.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:
```javascript
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:
```json
{
"navigationBarTitleText": "地图范围框"
}
```
2. 在app.json中将map页面添加到pages数组中:
```json
{
"pages": [
"pages/index/index",
"pages/map/map"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "WeChat",
"navigationBarTextStyle": "black"
}
}
```
3. 运行小程序,进入map页面即可在地图上触摸拖动时显示拖动范围框,并输出范围框左上角和右下角的经纬度。
原文地址: https://www.cveoy.top/t/topic/qAmM 著作权归作者所有。请勿转载和采集!