Swift中高效查询大型GeoJSON文件获取点所属限速区域
iOS Swift导航应用GeoJSON限速查询性能优化
问题背景
我有一个200MB的包含某国限速信息的GeoJSON文件,文件中用多边形划分不同区域,每个多边形对应一个限速值。目前正在开发一款iOS Swift导航应用,需要查询该GeoJSON文件以获取用户当前所在位置的限速。当前采用线性搜索方案,虽可运行但会导致应用卡顿,性能严重下降。
当前线性搜索实现代码
func findSpeedLimit(location: CLLocationCoordinate2D, geoJSON: GeoJSON) -> Int? { // Decode the GeoJSON data into a FeatureCollection object guard case let .featureCollection(featureCollection) = geoJSON else { print("Error: GeoJSON data is not a FeatureCollection") return nil } // Create a Point object from the location coordinates let point = Point(x: location.longitude, y: location.latitude) //print("Looking for speed limit at location: \(location.latitude), \(location.longitude)") // Loop through the features in the feature collection for (index, feature) in featureCollection.features.enumerated() { // Check if the feature has a geometry and properties guard let geometry = feature.geometry, let properties = feature.properties else { print("Feature \(index) has no geometry or properties") continue } do { // Check if the geometry contains the point if try geometry.contains(point) { // Check if the properties have a speedLimitZoneValue key if let speedLimit = properties["speedLimitZoneValue"] { let speedLimitString = String(describing: speedLimit) if let number = Int(speedLimitString.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) { //print (number) //print("Speed limit found for feature \(index): \(number) km/h") return number } } else { print("Feature \(index) has no 'speedLimitZoneValue' property") } } else { //print("Feature \(index) does not contain the point") } } catch { print("Error checking if geometry contains point: \(error)") } } return nil }
已完成的优化
借助GEOSwift库实现了预准备几何图形(prepared geometries),通过预编译多边形几何数据,大幅减少每次点-in-多边形判断的计算开销,避免线性搜索中重复的几何处理操作,有效提升查询性能。
内容的提问来源于stack exchange,提问作者Jesse_rs
相关产品推荐
相关产品推荐

