将经度和经度数组传递给swift中的CLLocationCoordinate2DMake

问题描述 投票:0回答:1

我有两个数组,一个包含纬度,第二个包含经度。我正试图将它传递给CLLocationCoordinate2DMake。从响应我得到纬度和经度,但他们是字符串格式。我正在将它转换为Double。但是,当我通过该阵列时,它向我显示错误Cannot convert value of type '[Double]' to expected argument type 'CLLocationDegrees' (aka 'Double')

我试过这段代码,

    var latitudeArray = [Double]()
var longitudeArray = [Double]()
latitudeArray = UserDefaults.standard.array(forKey: "latitudeArray") as! [Double]
    longitudeArray = UserDefaults.standard.array(forKey: "longitudeArray") as! [Double]

    print(latitudeArray)
    print(longitudeArray)
  let location = CLLocationCoordinate2DMake(latitudeArray, longitudeArray)
    mapView.setRegion(MKCoordinateRegionMakeWithDistance(location, 1500, 1500), animated: true)

    let pin = MapPin.init(title: name!, locationName: name!, coordinate: location)
    mapView.addAnnotation(pin).

我如何将我的阵列传递给它?我希望地图显示所有位置,我正在传递给它的lat和lng。

mapkit swift4
1个回答
2
投票

你的代码有一些缺陷。首先,CLLocationCoordinate2DMake为每个参数选择一个Double,而你正在尝试使用ArrayDouble。除了将你存储的所有坐标拟合到UserDefaults之外,你的代码有点不清楚你是否真的想要在地图上显示引脚,所以下面的代码同时执行这两个操作。

以下代码将

  • 采取一系列纬度和一系列经度
  • 将它们变成坐标对象
  • 将这些坐标转换为地图注释
  • 将这些注释添加到地图中
  • 缩放地图以适合所有注释

干得好!

    let latitudes = [Double]()
    let longitudes = [Double]()
    let names = [String]()

    let coordinates = zip(latitudes, longitudes).map(CLLocationCoordinate2D.init)

    let annotations = zip(coordinates, names)
        .map { (coordinate, name) -> MKPointAnnotation in
            let annotation = MKPointAnnotation()

            annotation.coordinate = coordinate
            annotation.title = name

            return annotation
        }

    map.addAnnotations(annotations)
    map.showAnnotations(annotations, animated: true)

来自showAnnotations文档:

设置可见区域,以便地图显示指定的注释。

© www.soinside.com 2019 - 2024. All rights reserved.