uniapp小程序地图电子围栏根据当前点的经纬度判断是否在多边形电子围栏范围内

原理参考链接
js如何判断地图上一个点在多边形内
uniapp实现电子围栏

<map class="my_map" id="myMap" show-location :latitude="latitude" :longitude="longitude" :markers="markers"
	:scale="mapScale" @regionchange="regionChange" @begin="begin" @end="end" @updated="mapUpDate"
	:subkey="null" :polygons="polygons">
</map>
data() {
    
    
	return {
    
    
		polygons: [
			{
    
    
				points: [{
    
    
						latitude: 29.600936,
						longitude: 106.513925,
					},
					{
    
    
						latitude: 29.601398,
						longitude: 106.515609
					},
					{
    
    
						latitude: 29.600997,
						longitude: 106.51724
					},
					{
    
    
						latitude: 29.602219,
						longitude: 106.517466
					},
					{
    
    
						latitude: 29.602121,
						longitude: 106.515524
					},
					{
    
    
						latitude: 29.60103,
						longitude: 106.513914
					},
				],
				strokeColor: "#FD302F",
				strokeWidth: 2,
				fillColor: "green"
			}
		], // 通过后端请求电子围栏经纬度集合
	}
}				
// 拖动地图后获取当前中心点的地图坐标
getCenterLoaction() {
    
    
	this.mapCtx.getCenterLocation({
    
    
		success: res => {
    
    
			// 更新地址信息
			// 如果存在多个电子围栏则去遍历该方法,判断是否在电子围栏范围内
			const isArea = this.isPointInPolygon(res.longitude, res.latitude, this.polygons[0].points)
			console.log('是否在电子围栏范围内', isArea)
			
		}
	});
},
// 判断点是否在多边形范围内
isPointInPolygon(lng, lat, polygon) {
    
    
	console.log(polygon)
	var cnt = 0;
	for (var i = 0; i < polygon.length; i++) {
    
    
		const g = lng;
		const t = lat;
		const p1g = polygon[i].longitude;
		const p1t = polygon[i].latitude;
		const p2g = polygon[i === polygon.length - 1 ? 0 : i + 1].longitude;
		const p2t = polygon[i === polygon.length - 1 ? 0 : i + 1].latitude;
		const ming = Math.min(p1g, p2g);
		const maxg = Math.max(p1g, p2g);
		const mint = Math.min(p1t, p2t);
		const maxt = Math.max(p1t, p2t);
		if ((mint <= t && t <= maxt && ming <= g) && (maxg <= g || (p2g + (p1g - p2g) * ((t - p2t) / (p1t -
				p2t)) < g))) {
    
    
			cnt++
		}
	}
	return cnt % 2 === 1;
},

猜你喜欢

转载自blog.csdn.net/weixin_38566069/article/details/131184574