我正在尝试在Google地图上显示位置,我从Firestore
获取了经度和纬度。
我创建了一个存储纬度和经度的结构
struct Location {
var latitude: String = ""
var longitute: String = ""
}
这是我的firestore代码,用于获取经度和纬度
for document in snapshot!.documents {
self.location.append(Location(latitude: "\(document.data()["Latitude"] ?? "")", longitute: "\(document.data()["longitude"] ?? "")"))
print(self.location)
guard let long = document.data()["Latitude"] as? String else { return}
guard let lat = document.data()["longitude"] as? String else { return}
let markerStart = GMSMarker(position: CLLocationCoordinate2D(latitude: Double(long) ?? 0.0, longitude: Double(lat) ?? 0.0))
markerStart.map = self.mapView
}
我正在控制台中找到位置,但是当我将其转换为Doubles并试图在Google地图上显示时,它无法正常工作。请帮忙吗?
Document Value is ["userid": 24xDkrtBV6cJrBvRD3U0PmyBF3o2, "createddatetime": FIRTimestamp: seconds=1546584489 nanoseconds=461000000>, "user_role": sales man, "Latitude": 20.6108261, "longitude": 72.9269003, "batterypercentage": 66, "name": Keyur , "company_code": 001]
答案 0 :(得分:1)
所以您有以下数据:
["userid": 24xDkrtBV6cJrBvRD3U0PmyBF3o2, "createddatetime": FIRTimestamp: seconds=1546584489 nanoseconds=461000000>, "user_role": sales man, "Latitude": 20.6108261, "longitude": 72.9269003, "batterypercentage": 66, "name": Keyur , "company_code": 001]
代替这种代码:
for document in snapshot!.documents {
self.location.append(Location(latitude: "\(document.data()["Latitude"] ?? "")", longitute: "\(document.data()["longitude"] ?? "")"))
print(self.location)
guard let long = document.data()["Latitude"] as? String else { return}
guard let lat = document.data()["longitude"] as? String else { return}
let markerStart = GMSMarker(position: CLLocationCoordinate2D(latitude: Double(long) ?? 0.0, longitude: Double(lat) ?? 0.0))
markerStart.map = self.mapView
}
我们可以像这样改善它
for document in snapshot!.documents {
self.location.append(Location(latitude: "\(document.data()["Latitude"] ?? "")", longitute: "\(document.data()["longitude"] ?? "")"))
print(self.location)
guard let latitude = document.data()["Latitude"] as? Double,
let longitude = document.data()["Latitude"] as? Double else { return }
let markerStart = GMSMarker(position: CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
markerStart.map = self.mapView
}
程序未到达第72 73 74行的原因是由于guard let
。无法将您假设的String
的经纬度从Double
转换为document.data()
。像我上面的代码一样做,然后您可以根据需要进一步改进它。