上图:
上代码:
在utils中:
//判断点是否在面中
function inArea(l, p) {
var minX = l[0].longitude,
maxX = l[0].longitude,
minY = l[0].latitude,
maxY = l[0].latitude;
for (var i = 1; i < l.length; i++) {
if (l[i].longitude < minX) {
minX = l[i].longitude;
}
if (l[i].longitude > maxX) {
maxX = l[i].longitude;
}
if (l[i].latitude < minY) {
minY = l[i].latitude;
}
if (l[i].latitude > maxY) {
maxY = l[i].latitude;
}
}
if (p.longitude < minX && p.longitude > maxX && p.latitude < minY && p.latitude > maxY) {
return false // 这个测试都过不了。。。直接返回false;
} else {
var vertx = [],
verty = [];
for (var i = 0; i < l.length; i++) {
vertx.push(l[i].longitude)
verty.push(l[i].latitude)
}
var c = pnpoly(l.length, vertx, verty, p.longitude, p.latitude);
return c;
}
}
function pnpoly(nvert, vertx, verty, testx, testy) {
var i, j, c = false;
for (i = 0, j = nvert - 1; i < nvert; j = i++) {
if (((verty[i] > testy) != (verty[j] > testy)) &&
(testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]))
c = !c;
}
return c;
}
module.exports = {
inArea: inArea,
}
在地图界面中: wxml
<view class="tbfb">
<map show-location="true" show-compass="true" style="width: 100%; height:100%"></map>
<map longitude="{{longitude}}" latitude="{{latitude}}"scale="14" show-location="true" bindtap="clickMapTap" markers="{{marks}}"
polygons="{{polygons}}"
bindmarkertap="markertap" style="width: 100%; height:1200rpx"/>
</view>
注意的是bindtap事件,其他的属性可以参考微信的api
JS:
clickMapTap: function(e) { //单击地图事件,在page中作为一个方法的存在。
//console.log("点击了地图"
// if (!false) {
// return
// }
var mark = new Object();//创建一个mark对象
mark.id = this.data.marks.length;
mark.longitude = e.detail.longitude; //经度
mark.latitude = e.detail.latitude;
mark.iconPath = "/images/point.png";//点图标,自己弄
mark.width = 10;
mark.height = 12;
//将点击得到的经纬度赋值
var point = {
longitude: e.detail.longitude,
latitude: e.detail.latitude
}
//声明 fw(范围)是一个坐标集合,可以自己找一些固定的点。
//(组织形式:[{lat,lng},{lat,lng}...]),
var inin = util.inArea(fw, point)//条用util中的判断方法
mark.label = {
fontSize: 25,
anchorX: -5,
anchorY: 0,
content: inin ? "在面内" : "在面外",
textAlign: 'center',
color: '#000000',
}
this.data.marks.push(mark);
this.setData({//在点击位置设置mark
marks: this.data.marks,
})
},
代码上完了,讲下流程,通过绑定地图的单击事件,然后判断点击的点是否在面内!
遇到的坑,1.首先地图中的polygons是一个面集合,所以不能用面对象直接塞进去,这样无法显示面,
2.maker的label是mark的一个对象属性,直接复制是没有问题的,
3.setData是用于界面数据更新的方法,所以等于号赋值是不起用作的
3.在page的顶端加上var util = require('../../utils/util.js');utils的路径,来获取工具类里面的方法
4.在utils中module.exports是用来映射方法的,所以如果不在里面添加上你写的方法是无法使用的
接下来实现了吗?欢迎提问。