在Swift 3.0中,可以使用以下代码将坐标数组转换为GeoJSON字符串:
import Foundation
struct Coordinate {
var latitude: Double
var longitude: Double
}
func convertToGeoJSON(coordinates: [Coordinate]) -> String? {
var featureCollection: [String: Any] = [
"type": "FeatureCollection",
"features": []
]
for coordinate in coordinates {
let feature: [String: Any] = [
"type": "Feature",
"geometry": [
"type": "Point",
"coordinates": [coordinate.longitude, coordinate.latitude]
],
"properties": [:]
]
featureCollection["features"]?.append(feature)
}
do {
let jsonData = try JSONSerialization.data(withJSONObject: featureCollection, options: [])
let jsonString = String(data: jsonData, encoding: .utf8)
return jsonString
} catch {
print("Error converting to GeoJSON: \(error)")
return nil
}
}
// Example usage:
let coordinates = [
Coordinate(latitude: 37.7749, longitude: -122.4194),
Coordinate(latitude: 34.0522, longitude: -118.2437),
Coordinate(latitude: 40.7128, longitude: -74.0060)
]
if let geoJSONString = convertToGeoJSON(coordinates: coordinates) {
print(geoJSONString)
} else {
print("Failed to convert coordinates to GeoJSON")
}
这段代码定义了一个Coordinate
结构体来表示经纬度坐标。convertToGeoJSON
函数将坐标数组转换为GeoJSON字符串。它首先创建一个空的FeatureCollection字典,并遍历坐标数组,为每个坐标创建一个Feature字典。然后,使用JSONSerialization
将FeatureCollection字典转换为JSON数据,并将其转换为字符串。
这个功能可以用于将一组坐标转换为GeoJSON格式,以便在地图上显示或进行其他地理信息处理。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云