用于查询地理空间数据集的iOS核心数据

时间:2011-05-22 00:08:51

标签: ios ios4 core-data

我正在使用核心数据框架来管理一组帐户,这些帐户还包括每个帐户的地理空间(GPS)坐标数据。如何根据设备的位置查询此数据以获取x英尺内的帐户列表并按距离的顺序列出?

1 个答案:

答案 0 :(得分:0)

开始使用,这是我在iOS应用程序中使用的一种方法,它返回两个CLLocationCoordinate2D位置之间的距离,假设是Google Spherical Mercator Projection(如果你想使用另一个投影,你可以指定适当的扁平率值(f)和半长轴值(a)。如果你想要坐标之间的前后方位角值,你可以通过定义你自己的结构取消注释并返回faz和baz值以及距离。这个方法可以用于添加到每个“帐户”对象的距离以及CLLocationManager对象报告的当前位置,然后您可以根据距离轻松地对帐户对象数组进行排序和过滤。

基于Gerald Evenden的代码:http://article.gmane.org/gmane.comp.gis.proj-4.devel/3478

#define PI 3.141592653589793238462643
#define EPS 5e-14
#define DEG_TO_RAD 0.0174532925199432958

// returns the geodesic distance in meters between two coordinates based on the google spherical mercator projection.
- (int) geodesicDistanceFromCoordinate: (CLLocationCoordinate2D) fromCoord toCoordinate: (CLLocationCoordinate2D) toCoord {
    double c, d, e, r, x, y, sa, cx, cy, cz, sx, sy, c2a, cu1, cu2, su1, tu1, tu2, ts, phi1, lam1, phi2, lam2, f, baz, faz, s, a;

    phi1 = fromCoord.latitude * DEG_TO_RAD;
    lam1 = fromCoord.longitude * DEG_TO_RAD;
    phi2 = toCoord.latitude * DEG_TO_RAD;
    lam2 = toCoord.longitude * DEG_TO_RAD;
    f = 0;  //google's spherical mercator projection has no flattening
    a = 6378137;  //earth's axis in meters used in google's projection

    r = 1. - f;
    tu1 = r * tan(phi1);
    tu2 = r * tan(phi2);
    cu1 = 1. / sqrt(tu1 * tu1 + 1.);
    su1 = cu1 * tu1;
    cu2 = 1. / sqrt(tu2 * tu2 + 1.);
    ts = cu1 * cu2;
    baz = ts * tu2;
    faz = baz * tu1;
    x = lam2 - lam1;

    do {
        sx = sin(x);
        cx = cos(x);
        tu1 = cu2 * sx;
        tu2 = baz - su1 * cu2 * cx;
        sy = sqrt(tu1 * tu1 + tu2 * tu2);
        cy = ts * cx + faz;
        y = atan2(sy, cy);
        sa = ts * sx / sy;
        c2a = -sa * sa + 1.;
        cz = faz + faz;
        if (c2a > 0.)
            cz = -cz / c2a + cy;
        e = cz * cz * 2. - 1.;
        c = ((c2a * -3. + 4.) * f + 4.) * c2a * f / 16.;
        d = x;
        x = ((e * cy * c + cz) * sy * c + y) * sa;
        x = (1. - c) * x * f + lam2 - lam1;
    } while (fabs(d - x) > EPS);

//forward azimuth    faz = atan2(tu1, tu2);
//backward azimuth    baz = atan2(cu1 * sx, baz * cx - su1 * cu2) + PI;
    x = sqrt((1. / r / r - 1.) * c2a + 1.) + 1.;
    x = (x - 2.) / x;
    c = (x * x / 4. + 1.) / (1. - x);
    d = (x * .375 * x - 1.) * x;
    s = ((((sy * sy * 4. - 3.) * (1. - e - e) * cz * d / 6. - e * cy) * d / 4. + cz) * sy * d + y) * c * r;
    return (int)(s * a);
}