从XCode中的SQLite数据库获取特定半径内的所有位置

时间:2015-06-20 07:36:38

标签: iphone swift sqlite location

我有一个SQLite数据库,其中包含多个位置的纬度和经度。

我想从我的SQLite数据库中找到距离我当前位置15公里半径范围内的所有位置的纬度和经度。

我的SQLite查询是什么?

3 个答案:

答案 0 :(得分:2)

纬度的一度差等于111 km距离,经度的一度差等于94 km。所以现在检查处于(+/-)(15/111)差异和经度的所有纬度,它们与当前位置的差异为(+/-)(15/94)。 重要link以供参考。

答案 1 :(得分:1)

要按升序排列它们,请将所有distcnace存储在带有键的字典中。等,

 distanceDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithFloat:distanceVal],@"distance",nil];

 [distanceArray addObject:distanceDic];

这里,distanceDic是我的词典,distaceVal是包含距离的字符串。 distanceArray是包含距离的NSMutableArray。 现在对distanceDic进行排序,比如

NSArray *array = [NSArray arrayWithArray:[distanceArray mutableCopy]]; // Copying NSMutableArray to NSArray.
NSSortDescriptor *sortDescriptor;

sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES];

NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

array = [array sortedArrayUsingDescriptors:sortDescriptors];

NSLog(@"#The Final Distance Array After Sorting :%@",array);

这将为您提供按升序排序的结果距离数组。

答案 2 :(得分:0)

对于仍在寻找答案的人:

您可以使用@breceivemail's answer [JAVA]

改编的此方法来获取附近的地点

以下是Swift中的翻译版本:

private func calculateDerivedPosition(point: CGPoint, range: Double, bearing: Double)-> CGPoint {
    let EarthRadius: Double = 6371000

    let latA = Double(point.x.degreesToRadians)
    let lonA = Double(point.y.degreesToRadians)
    let angularDistance = range / EarthRadius
    let trueCourse = bearing.degreesToRadians

    var lat = asin(sin(latA) * cos(angularDistance) +
                   cos(latA) * sin(angularDistance) *
                   cos(trueCourse))

    let dlon = atan2(sin(trueCourse) * sin(angularDistance) * cos(latA),
                     cos(angularDistance) - sin(latA) * sin(lat))

    var lon = ((lonA + dlon + Double.pi).truncatingRemainder(dividingBy: (Double.pi * 2))) - Double.pi

    lat = lat.radiansToDegrees
    lon = lon.radiansToDegrees

    let newPoint = CGPoint(x: lat, y: lon)

    return newPoint
} 

radiansToDegree Extension

你可以像FMDB(或任何Sqlite lib)一样使用它:

    let center = CGPoint(x: currentLocation.latitude, y: currentLocation.longitude)
    let mult: Double = 1 // mult = 1.1 is more reliable
    let radius: Double = 5000 //in meters

    let point1 = calculateDerivedPosition(point: center, range: radius * mult, bearing: 0)
    let point2 = calculateDerivedPosition(point: center, range: radius * mult, bearing: 90)
    let point3 = calculateDerivedPosition(point: center, range: radius * mult, bearing: 180)
    let point4 = calculateDerivedPosition(point: center, range: radius * mult, bearing: 270)

    let result = try!db.executeQuery("SELECT * FROM items WHERE lat > ? AND lat < ? AND lng < ? AND lng > ?" , values: [point3.x, point1.x, point2.y, point4.y])

注意:结果未排序。