我有一些存储在Core Data中的位置(在本例中>3000 )。打开地图后,获取位置并将其存储在数组中。每次mapview区域更改时,我都会调用一个函数,该函数将计算哪些注释在当前visibleMaprect中可见,并根据像素距离对它们进行过滤。(我知道会有更复杂的优化,比如四叉树,但如果不是非常必要的话,我现在不会真正实现它)。这是我的代码:
//locations is an array of NSManagedObjects
for (int i =0 ; i < [locations count]; i++)
{
// managed object class for faster access, valueforkey takes ages ...
LocationEntity * thisLocation = [locations objectAtIndex:i];
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake( [thisLocation.latitude doubleValue], [thisLocation.longitude doubleValue]) ;
// mapRect is mapView.visibleMapRect
BOOL isOnScreen = MKMapRectContainsPoint(mapRect, MKMapPointForCoordinate(coord));
if (isOnScreen)
{
CGPoint cgp = [mapView convertCoordinate:coord toPointToView:mapView];
// compare the distance to already existing annotations
for (int idx = 0; idx < [annotations count] && hasEnoughDistance; idx++)
{
CGPoint cgp_prev = [mapView convertCoordinate:[[annotations objectAtIndex:idx] coordinate] toPointToView:mapView];
if ( getDist(cgp, cgp_prev) < dist ) hasEnoughDistance = FALSE;
}
}
if (hasEnoughDistance)
// if it's ok, create the annotation, add to an array and after the for add all to the map
}每次缩放/移动后,地图都会冻结几秒钟。我查看了time profiler,简单的坐标获取有时需要1整秒,有时只需要0.1秒,即使坐标在我的模型中是索引属性……此外,这些类型的线路似乎需要很长时间:CGPoint cgp = [mapView convertCoordinate:coord toPointToView:mapView];
有什么建议吗?我如何计算两个注释/坐标之间的像素/点距离,而不是通过这个函数?或者对核心数据有什么优化建议?
谢谢:)
发布于 2012-09-28 18:02:31
好的,我有点错过了你的解释中没有太接近它们的部分。坐标之间的转换非常慢。可以缓解这种情况的方法是使用MKMapPointForCoordinate将坐标预先计算成地图点,并持久地存储它们-它们只依赖于坐标。然后,您可以快速计算两个注记的地图点之间的距离,根据地图的当前缩放级别对其进行缩放,这将与屏幕上的实际距离密切相关。它应该足够准确,而且会快得多。
我建议计算平方距离,并将其与平方dist进行比较。你会在sqrt()上节省很多钱。
如果您仍然在getDist() (或getSqDist())上遇到困难,您可以使用kd树或使用加速框架来进行计算。当我需要计算许多点之间的距离时,我已经使用了后者,并且加速效果非常好。但这件事的细节是另一回事。如果你需要任何帮助,请告诉我。
您的坐标被编入索引的事实只有在您实际通过坐标搜索注释时才会有帮助,所以如果您只是查看所有的注释,那么它不会有任何帮助。
处理从CoreData加载时间过长的一种方法是尝试使您的注释尽可能轻量级,以便只存储坐标和地图点。然后,您就可以根据需要获得其余的注释数据。这可以使用代理模式来完成。
还有一件事。快速枚举可能会更快,也是更好的做法,因此
for(LocationEntity* thisLocation in locations)而不是
for (int i =0 ; i < [locations count]; i++)https://stackoverflow.com/questions/12637803
复制相似问题