将字符串从 CoreData 转换为 CLLocationDegrees/ CLLocationCoordinate2D

Convert String from CoreData into CLLocationDegrees/ CLLocationCoordinate2D

我一直在努力将 google 地图上标记的 CLLocationCoordinate2D 数据存储到 CoreData。这不能直接完成,但我找到了一个解决方法,我可以在其中获取坐标,拆分为 CLLocationDegrees,将其转换为字符串文本并存储。我通过以下方式做到这一点:

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(place.coordinate.latitude, place.coordinate.longitude)

    let newPlaceLatitude = place.coordinate.latitude
    print(newPlaceLatitude)
    var latitudeText:String = "\(newPlaceLatitude)"
   self.latitudeText = "\(newPlaceLatitude)"
    let newPlaceLongitude = place.coordinate.longitude
    print(newPlaceLongitude)
    var longitudeText:String = "\(newPlaceLongitude)"
self.longitudeText = "\(newPlaceLongitude)"

存储到 CoreData:

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newPlace = NSEntityDescription.insertNewObject(forEntityName: 
     "StoredPlace", into: context)
     newPlace.setValue(latitudeText, forKeyPath: "latitude")
    newPlace.setValue(longitudeText, forKeyPath: "longitude")

但是现在我正在努力将字符串重建回 CLLocationCoordinates。我如何将字符串转换为 CLLocationDegree/CLLocationCoordinate2D ?这应该很简单,但我发现以下方法不起作用:

    let latitude:  CLLocationDegrees = Double(latitudeText)!
                let longitude: CLLocationDegrees = Double(longitudeText)!
                    let markers = GMSMarker()
                print(latitude)
                print(longitude)
                    markers.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

关于如何将字符串更改为坐标的任何其他建议?

CLLocationlatitudelongitude 是双打,因此考虑到这一点,您可以考虑使用 latitudelongitude 属性在你的 StoredPlace 对象上加倍。我将属性命名为 coordinateXcoordinateY 以便更容易记住它们是自定义坐标,而不是 "factory" 属性。

您可以在名为 StoredPlace+Extension.swift 的文件中创建扩展,如下所示:

import CoreData
import CoreLocation

extension StoredPlace {
    func location() -> CLLocation {
        let location = CLLocation(latitude: self.coordinateX, longitude: self.coordinateY)
        return location
    }
}

使用此扩展程序,您可以按如下方式从结果中获取坐标:

for result in results {
    print("coordinate = \(result.location().coordinate)")
    print("latitude = \(result.location().coordinate.latitude)")
    print("longitude = \(result.location().coordinate.longitude)")
}

您需要 typecast 您的纬度和经度的十进制值,更可取的是 double 而不是 float,因为精度值可以将图钉放在完美的位置。

double 中使用 as 关键字进行类型转换:

(yourCordinateString as NSString).doubleValue

转换为 float 值:

(yourCordinateString as NSString).floatValue