2010-10-21 46 views
6

我想要做的是:用户选择地图上的开始和目的地,然后从他们的坐标中我想显示地图上的位置列表中的最近点位置。我有一个简单的Sqlite数据库,其中包含可能位置的经度,纬度和名称。找到最近的Gps指向用户位置形成一个列表

我做了一些研究,这是我发现:

http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL

,但这是为使用它与MySQL和某种空间搜索扩展。 有没有可能使用android api或external libs做类似的事情?

public Point dialogFindClosestLocationToPoint(geometry.Point aStartPoint){ 
List<PointWithDistance> helperList=new ArrayList<PointWithDistance>(); 
try { 
openDataBase(); 
Cursor c=getCursorQueryWithAllTheData(); 
if(c.moveToFirst()) 
do{ 
    PointWithDistance helper=new PointWithDistance(c.getDouble(1),c.getDouble(2),c.getString(3)); 
    int distance=returnDistanceBetween2Points(aStartPoint, helper); 
    if(distance<MAX_SEARCH_DISTANCE){ 
    helper.setDistance(distance); 
    Log.i("values", helper.name); 
    helperList.add(helper); 
    } 
}while (c.moveToNext()); 
Collections.sort(helperList,new PointComparator()); 

if(helperList!=null) 
return helperList.get(0); 
else return null; 
}catch(SQLException sqle){ 

throw sqle; 

} 
finally{ 
close(); 
} 

这是在PointComparator()类的代码:

public int compare(PointWithDistance o1, PointWithDistance o2) { 
    return (o1.getDistance()<o2.getDistance() ? -1 : (o1.getDistance()==o2.getDistance() ? 0 : 1)); 
} 

PointWithDistance哪里是包含一个对象:纬度,经度,距离,名称

然而这种解决方案不提供正确的回报信息......我意识到这是不可扩展的,而且非常缓慢。我需要一个解决方案,该解决方案可以用最多1000行的数据库快速执行。

编辑:我有这个代码现在分拣错误我把它换成(应该是<代替>)

回答

2

我一直在寻找一些非常相似,前一段时间:

Android sqlite sort on calculated column (co-ordinates distance)

我是用我的服务器上一个MySQL查询,MySQL允许你创建一个虚拟列,执行由距离计算和排序,然后你可以设置最大结果返回或最大距离 - 它工作得很好:

Select Lat, Lon, acos(sin($lat)*sin(radians(Lat)) + cos($lat)*cos(radians(Lat))cos(radians(Lon)-$lon))$R As dist From MyTable ORDER BY dist DESC 

我想在我的应用程序执行相同的操作 - 为了从用户locati拉开距离拉的所有点让我展示最接近的。我最终选择了上述链接中提出的解决方案,但意识到它可能不是最佳解决方案,但是可以达到我想要的目的。

+0

我相信你已经通过PHP传递变量。 $ lat是您当前的纬度,$ lon是当前的纬度。但是什么是$ R? – 2012-12-16 19:54:00

+0

不是$ R地球半径?请参阅:http://www.movable-type.co.uk/scripts/latlong.html – leochab 2013-07-05 07:08:15

1

我还没有试过运行你的代码,但它似乎将工作,只是它效率不高。就像你实际上不需要排序一样,你需要的是最少的提取。

你可以限制你的查询只是大小为(2 * MAX_SEARCH_DISTANCE)^ 2(用你的点在中间的方格) 这样你就可以本地化你的查询,并且这会返回给你更少的结果来计算距离(?也许不太可能)。对于 当然,这不会帮助,如果您的所有地点都在本地化广场

另外,我想你可以使用,而不是欧氏哈密顿距离 欧几里得距离=开方((lat0 - lat1)^ 2 +(lon0 - lon1)^ 2) hamitonian distance =(lat0-lat1)+(lon0 - lon1)

+0

我实际上使用Android Location api中定义的函数来计算两个gps坐标之间的距离。因为我发现它非常精确,它也考虑到地球的形状。 “你需要提取的最低限度。”什么是最好的方式来做到这一点? – DArkO 2010-10-21 18:08:13

3

Thi使用R-Tree可以最有效地完成某种事情。 JSI library提供了一个Java实现,我成功地使用了80,000个位置的索引,每秒处理数千次查找。但是,它可能无法在Android上运行。

+0

是的,我发现一些信息,r-树是一个很好的解决方案,但我还没有找到任何Android的图书​​馆到目前为止。我会继续寻找并尝试上面提到的。 – DArkO 2010-10-21 18:19:25