The uniapp applet map electronic fence judges whether it is within the polygonal electronic fence range according to the latitude and longitude of the current point

Principle reference link
js how to judge that a point on the map is within the polygon
uniapp realizes electronic fence

<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;
},

Guess you like

Origin blog.csdn.net/weixin_38566069/article/details/131184574