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

index.html

``````<!DOCTYPE html>
<html>

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

<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, ' +
id: 'mapbox.streets'
.bindPopup("<b>Hello world!</b><br />我是一个冒泡窗").openPopup();
L.circle([24, 100], 500, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5
L.polygon([{
lat: 26,
lng: 101
}, {
lat: 24,
lng: 120
}, {
lat: 35,
lng: 110
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());
}
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;
}``````