将CoreData中的字符串转换为CLLocationDegrees / CLLocationCoordinate2D

时间:2016-12-31 12:49:50

标签: ios swift core-data coordinates cllocation

我一直在努力将谷歌地图上的标记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)

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

2 个答案:

答案 0 :(得分:1)

CLLocation latitudelongitude是双打的,所以考虑到这一点,您可能会考虑拥有latitudelongitude属性是StoredPlace对象上的双打。我调用了属性coordinateXcoordinateY,因此更容易记住他们是自定义坐标,而不是"工厂"属性。

您可以在名为 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)")
}

答案 1 :(得分:0)

你需要typecast你的lat和long十进制值,更优选的是double而不是float,因为精度值会使引脚在完美的位置掉落。

使用关键字在double中输入信息:

(yourCordinateString as NSString).doubleValue

投射float值:

(yourCordinateString as NSString).floatValue
相关问题