PHP 坐标位于多边形内

PHP 坐标位于多边形内

复制自:https://www.cnblogs.com/heyangyi/p/8562610.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* 判断坐标是否在坐标区间范围内
*
* @param array $check_point 判断坐标
* @param array $polygon_points 坐标区间范围
* @return bool
*/
function is_in_polygon(array $check_point, array $polygon_points) {
$counter = 0;
$p1 = $polygon_points[0];
$point_count = count($polygon_points);

for($i = 1; $i <= $point_count; $i++) {
$p2 = $polygon_points[$i % $point_count];
if (
$check_point[0] > min($p1[0], $p2[0]) &&
$check_point[0] <= max($p1[0], $p2[0])
) {
if ($check_point[1] <= max($p1[1], $p2[1])) {
if ($p1[0] != $p2[0]) {
$xinters =
($check_point[0] - $p1[0]) *
($p2[1] - $p1[1]) /
($p2[0] - $p1[0]) +
$p1[1];
if ($p1[1] == $p2[1] || $check_point[1] <= $xinters) {
$counter++;
}
}
}
}
}

return $counter % 2 != 0;
}

// -------------------------
// 测试
// 在范围内返回 true
is_in_polygon(
[113.27239573001862, 23.09122994009315],
[
[113.2675838470459, 23.09250306837517],
[113.2714033126831, 23.08877247232314],
[113.27876329421997, 23.093095216954744],
[113.2675838470459, 23.09250306837517]
]
);

// 在不范围内返回 false
is_in_polygon(
[113.27332377433777, 23.093411028463525],
[
[113.2675838470459, 23.09250306837517],
[113.2714033126831, 23.08877247232314],
[113.27876329421997, 23.093095216954744],
[113.2675838470459, 23.09250306837517]
]
);
往上