Ram*_*ish 3 mapkit ios swift swiftui
我使用下面的代码来加载地图,但结果出来后,地图仍然以用户位置为中心而不是注释周围,因为我必须滚动到图钉才能看到。
Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: searchResults) { dest in
MapAnnotation(coordinate: dest.coordinate, anchorPoint: CGPoint(x: 0.5, y: 0.5)) {
MapPin(coordinate)
}
}
Run Code Online (Sandbox Code Playgroud)
要更改地图显示的内容,您只需更改region其绑定的 ( coordinateRegion: $region)。改变它center会移动地图。要对缩放进行操作,您必须对span属性进行操作。
我已经建议您将卡移动到searchResults数组的第一个元素:
Map(coordinateRegion: $region, annotationItems: searchResults) {result in
MapMarker(coordinate: result.coordinate)
}
.onChange(of: searchResults) {newValue in
if let result = newValue.first {
region.center = result.coordinate
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您想移动(并放大/缩小)地图以使其包含所有结果:
Map(coordinateRegion: $region, annotationItems: searchResults) { result in
MapMarker(coordinate: result.coordinate)
}
.onChange(of: searchResults) { _ in
if !searchResults.isEmpty {
region = regionThatFitsTo(coordinates: searchResults.map { $0.coordinate })
}
}
Run Code Online (Sandbox Code Playgroud)
以及计算适合区域的函数:
func regionThatFitsTo(coordinates: [CLLocationCoordinate2D]) -> MKCoordinateRegion {
var topLeftCoord = CLLocationCoordinate2D(latitude: -90, longitude: 180)
var bottomRightCoord = CLLocationCoordinate2D(latitude: 90, longitude: -180)
for coordinate in coordinates {
topLeftCoord.longitude = fmin(topLeftCoord.longitude, coordinate.longitude)
topLeftCoord.latitude = fmax(topLeftCoord.latitude, coordinate.latitude)
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, coordinate.longitude)
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, coordinate.latitude)
}
var region: MKCoordinateRegion = MKCoordinateRegion()
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.4
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.4
return region
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1456 次 |
| 最近记录: |