如何在 iOS 中使用多个注释增加 Apple Mapkit 的缩放比例

问题描述

我试过这段代码在这里我将 MKCoordinateSpan 增加到 200 - 200,但我的应用程序崩溃了,有人可以帮我。

 func setupMap(hotelListData:[HotelListData],cityLocation: 
                CLLocationCoordinate2D )
   {

    let coordinateRegion = MKCoordinateRegion(center: cityLocation,span: MKCoordinateSpan(latitudeDelta: 200,longitudeDelta: 200))
    mapView.setRegion(coordinateRegion,animated: true)

    //Set Multiple Annotation
    for data in hotelListData {
        let annotation = MKPointAnnotation()
        annotation.title = data.hotel?.name
        annotation.coordinate = CLLocationCoordinate2D(latitude: Double(data.hotel?.latitude ?? 0.0),longitude: Double(data.hotel?.longitude ?? 0.0))
        mapView.addAnnotation(annotation)
    }
}

更新:

我从(latitudinalMeters & VerticalMeters)改变了跨度并得到了想要的结果:-

现在可以在这里找到:

i)为苹果地图设置多个注释。

ii) 根据所需位置调整缩放。

  func setupMap(hotelListData:[HotelListData],cityLocation: 
                 CLLocationCoordinate2D ){
    
    let coordinateRegion = MKCoordinateRegion(center: cityLocation,latitudinalMeters: CLLocationdistance(exactly: 15000)!,longitudinalMeters: CLLocationdistance(exactly: 15000)!)
    mapView.setRegion(coordinateRegion,longitude: Double(data.hotel?.longitude ?? 0.0))
        mapView.addAnnotation(annotation)
    }
}

解决方法

MKCoordinateSpanlongitudeDeltalatitudeDelta 以度为单位。从北极到南极只有 180 度的纬度,因此将该参数设为 200 不太明智。

由于您只想在地图上显示一个城市的区域,如果您知道您的应用通常处理的城市有多大,您可以使用 this other initialiser 以米为单位计算距离。

>

例如

let coordinateRegion = MKCoordinateRegion(center: cityLocation,latitudinalMeters: 30000,longitudinalMeters: 30000)

如果您的城市大小不一,或者您不知道它们有多大,那么另一种方法是计算酒店的经纬度范围,然后使用它来创建 MKCoordinateSpan

var minLat: CLLocationDegrees = 90
var maxLat: CLLocationDegrees = -90
var minLong: CLLocationDegrees = 180
var maxLong: CLLocationDegrees = -180
for data in hotelListData {
    // ... you annotation code ...

    guard let hotel = data.hotel else { continue }
    if hotel.latitude < minLat { minLat = hotel.latitude }
    if hotel.latitude > maxLat { maxLat = hotel.latitude }
    if hotel.longitude < minLong { minLong = hotel.longitude }
    if hotel.longitude > maxLong { maxLong = hotel.longitude }
}
let latRange = max(0.01,maxLat - minLat) // if the range is too small,make it at least 0.01
let longRange = max(0.01,maxLong - minLong)
let coordinateRegion = MKCoordinateRegion(
                           center: cityLocation,span: MKCoordinateSpan(latitudeDelta: latRange,longitudeDelta: longRange)