SwiftUI 判断用户是否处于地图上的某一区域内

将用户以及围成区域的点的坐标全部转换为 MKMapPoint,再绘制路径,最后判断用户的点是否被路径包含。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let point1: MKMapPoint = MKMapPoint(hexagon.points[0])
let point2: MKMapPoint = MKMapPoint(hexagon.points[1])
let point3: MKMapPoint = MKMapPoint(hexagon.points[2])
let point4: MKMapPoint = MKMapPoint(hexagon.points[3])
let point5: MKMapPoint = MKMapPoint(hexagon.points[4])
let point6: MKMapPoint = MKMapPoint(hexagon.points[5])

let path = UIBezierPath()
path.move(to: CGPoint(x: point1.x, y: point1.y))
path.addLine(to: CGPoint(x: point2.x, y: point2.y))
path.addLine(to: CGPoint(x: point3.x, y: point3.y))
path.addLine(to: CGPoint(x: point4.x, y: point4.y))
path.addLine(to: CGPoint(x: point5.x, y: point5.y))
path.addLine(to: CGPoint(x: point6.x, y: point6.y))
path.addLine(to: CGPoint(x: point1.x, y: point1.y))
path.close()

if path.contains(CGPoint(x: userPosition.x, y: userPosition.y)) {
...
}

SwiftUI 判断用户是否处于地图上的某一区域内
https://wonderhoi.com/2024/11/21/SwiftUI-判断用户是否处于地图上的某一区域内/
作者
wonderhoi
发布于
2024年11月21日
许可协议