繁体   English   中英

将String从CoreData转换为CLLocationDegrees / CLLocationCoordinate2D

[英]Convert String from CoreData into CLLocationDegrees/ CLLocationCoordinate2D

我一直在努力从Google地图上的标记存储到CoreData的CLLocationCoordinate2D数据。 这不能直接完成,但是我找到了一种解决方法,可以将坐标取为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是双精度的,因此,考虑到这一点,您可以考虑在StoredPlace对象上使用双精度的latitudelongitude属性。 我将属性称为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)")
}

您需要以十进制值typecast纬度和经度,更可取的是使用double而不是float,因为精度值可能会在理想位置掉线。

使用as关键字以double键入强制类型转换:

(yourCordinateString as NSString).doubleValue

转换为float值:

(yourCordinateString as NSString).floatValue

暂无
暂无

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

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