繁体   English   中英

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

[英]How can i increase zoom in Apple Mapkit with multiple annotations in iOS

我尝试了这段代码,在这里我将 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&longitudinalMeters)并得到了预期的结果: -

现在可以在这里找到:

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

ii) 使用所需位置调整缩放。

  func setupMap(hotelListData:[HotelListData], cityLocation: 
                 CLLocationCoordinate2D ){
    
    let coordinateRegion = MKCoordinateRegion(center: cityLocation, latitudinalMeters: CLLocationDistance(exactly: 15000)!, longitudinalMeters: CLLocationDistance(exactly: 15000)!)
    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)
    }
}

MKCoordinateSpanlongitudeDeltalatitudeDelta以度为单位。 从北极到南极只有 180 度的纬度,因此使用 200 作为该参数不是很明智。

由于您只想在地图上显示一个城市的区域,如果您知道您的应用程序通常处理的城市有多大,您可以使用另一个以米为单位的初始化程序。

例如,

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM