【问题标题】:Trying to simulate a route in MapView尝试在 MapView 中模拟路线
【发布时间】:2012-10-16 15:42:45
【问题描述】:

我有一个从文件中解析的CLLocation 对象数组。我想模拟用户沿着这条路线移动,我已经实现了这个:

for (CLLocation *loc in simulatedLocs) {
            [self moveUser:loc];
            sleep(1);
        }

这是循环中调用的方法:

- (void)moveUser:(CLLocation*)newLoc
{
    CLLocationCoordinate2D coords;
    coords.latitude = newLoc.coordinate.latitude;
    coords.longitude = newLoc.coordinate.longitude;
    CustomAnnotation *annotation = [[CustomAnnotation alloc] initWithCoordinate:coords];
    annotation.title = @"User";

    // To remove the previous location icon
    NSArray *existingpoints = self.mapView.annotations;
    if ([existingpoints count] > 0) {
        for (CustomAnnotation *annotation in existingpoints) {
            if ([annotation.title isEqualToString:@"User"]) {
                [self.mapView removeAnnotation:annotation];
                break;
            }
        }
    }

    MKCoordinateRegion region = { coords, {0.1, 0.1} };
    [self.mapView setRegion:region animated:NO];
    [self.mapView addAnnotation: annotation];
    [self.mapView setCenterCoordinate:newLoc.coordinate animated:NO];
}

但在运行 iPhone 模拟器时,只有数组中的最后一个位置及其区域会显示在 mapView 中。我想模拟用户每 1 秒“移动”一次,我该怎么做?

谢谢!

【问题讨论】:

  • 永远不要这样使用sleep

标签: iphone ios ios5 mkmapview mapkit


【解决方案1】:

在每次迭代中使用 sleep 一次循环遍历所有位置将不起作用,因为 UI 将被阻塞,直到循环所在的方法完成。

相反,安排为每个位置单独调用 moveUser 方法,以便 UI 在整个序列中不会被阻塞。可以使用NSTimer 或更简单、更灵活的方法(例如performSelector:withObject:afterDelay: 方法)来完成调度。

保留索引 ivar 以跟踪每次调用 moveUser 时要移动到的位置。

例如:

//instead of the loop, initialize and begin the first move...
slIndex = 0;  //this is an int ivar indicating which location to move to next
[self manageUserMove];  //a helper method

-(void)manageUserMove
{
    CLLocation *newLoc = [simulatedLocs objectAtIndex:slIndex];

    [self moveUser:newLoc];

    if (slIndex < (simulatedLocs.count-1))
    {
        slIndex++;
        [self performSelector:@selector(manageUserMove) withObject:nil afterDelay:1.0];
    }
}

现有的moveUser: 方法不必更改。


请注意,如果不是每次都重新删除和添加注释,而是在开始时添加一次并在每次“移动”时更改其coordinate 属性,则可以简化用户体验和代码。

【讨论】:

  • 谢谢,我终于决定使用performSelector 方法,并将我的moveUser 方法更改为只更新坐标而不是删除和添加新注释。现在它可以像我想要的那样工作了,谢谢 :) 谢谢大家的回复!
【解决方案2】:

您不应该使用 MKAnnotation,而是使用 MKPolyline。检查documentation。另外,请查看 2010 年的 WWDC MapKit 视频。它有一个可变 MKPolyline 的示例。

【讨论】:

  • 我正在使用注释,因为我想以与默认情况下为用户位置显示的蓝点类似的方式为当前位置绘制一个图标...我不想绘制完整的路线,我只想一步一步地绘制位置,就像用户在走路一样
【解决方案3】:

您的问题是其中包含睡眠的 for 循环阻塞了主线程,直到 for 循环结束。这会在整个期间冻结整个用户界面,包括您在 moveUser 中所做的任何更改。

使用每秒触发一次并且每次执行一个步骤的 NSTimer 来代替 for 循环。

或者,为了获得更平滑的效果,设置一个动画,沿预定义的路径移动注释的位置。

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    相关资源
    最近更新 更多