给定坐标点,判断是否在某区域范围内 地理围栏算法

地图平台:leaflet

语言:js

index.html

<!DOCTYPE html>
<html>

	<head>
		<title>Leaflet 快速开始指南示例</title>
		<meta charset="utf-8" />

		<link rel="stylesheet" href="css/leaflet.css" />
	</head>

	<body>
		<div id="map" style="width: 1024px; height: 768px"></div>

		<script src="js/leaflet.js"></script>
		<script type="text/javascript" src="js/jquery-2.0.3.min.js"></script>
		<script type="text/javascript" src="js/isPointInPolygon.js"></script>
		<script>
			var map = L.map('map').setView([24, 110], 5);
			L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6IjZjNmRjNzk3ZmE2MTcwOTEwMGY0MzU3YjUzOWFmNWZhIn0.Y8bhBaUMqFiPrDRW9hieoQ', {
				maxZoom: 18,
				attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
					'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
					'Imagery © <a href="http://mapbox.com">Mapbox</a>',
				id: 'mapbox.streets'
			}).addTo(map);
			L.marker([24, 100]).addTo(map)
				.bindPopup("<b>Hello world!</b><br />我是一个冒泡窗").openPopup();
			L.circle([24, 100], 500, {
				color: 'red',
				fillColor: '#f03',
				fillOpacity: 0.5
			}).addTo(map).bindPopup("我是一个圆");
			L.polygon([{
				lat: 26,
				lng: 101
			}, {
				lat: 24,
				lng: 120
			}, {
				lat: 35,
				lng: 110			
			}]).addTo(map);
			var popup = L.popup();

			function points() {
				var points = [{
				lat: 26,
				lng: 101
			}, {
				lat: 24,
				lng: 120
			}, {
				lat: 35,
				lng: 110
			}]
				return points;
			}

			function onMapClick(e) {
				popup
					.setLatLng(e.latlng)
					.setContent("你刚点击的坐标是 " + e.latlng.toString())
					.openOn(map);
				/*var hh = IsPtInPoly(119.44336,25.20494, points());*/
				var hh = IsPtInPoly(e.latlng.lng,e.latlng.lat, points());
				alert(hh);
			}
			map.on('click', onMapClick);
		</script>
	</body>

</html>

isPointInPolygon.js

function IsPtInPoly(ALon, ALat, APoints) {
	var iSum = 0,
		iCount;
	var dLon1, dLon2, dLat1, dLat2, dLon;
	if (APoints.length < 3) return false;
	iCount = APoints.length;
	for (var i = 0; i < iCount; i++) {
		if (i == iCount - 1) {
			dLon1 = APoints[i].lng;
			dLat1 = APoints[i].lat;
			dLon2 = APoints[0].lng;
			dLat2 = APoints[0].lat;
		} else {
			dLon1 = APoints[i].lng;
			dLat1 = APoints[i].lat;
			dLon2 = APoints[i + 1].lng;
			dLat2 = APoints[i + 1].lat;
		}
		//以下语句判断A点是否在边的两端点的水平平行线之间,在则可能有交点,开始判断交点是否在左射线上
		if (((ALat >= dLat1) && (ALat < dLat2)) || ((ALat >= dLat2) && (ALat < dLat1))) {
			if (Math.abs(dLat1 - dLat2) > 0) {
				//得到 A点向左射线与边的交点的x坐标:
				dLon = dLon1 - ((dLon1 - dLon2) * (dLat1 - ALat)) / (dLat1 - dLat2);
				if (dLon < ALon)
					iSum++;
			}
		}
	}
	if (iSum % 2 != 0)
		return true;
	return false;
}

转载自:https://blog.csdn.net/neil89/article/details/50240481

You may also like...