本文介绍了试图在MapView中模拟路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of CLLocation objects I parsed from a file. I'd want to simulate that the user is moving along that route, and I have implemented this:

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

这是循环中调用的方法:

This is the method called in the loop:

- (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];
}

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

But only last location in the array and its region are displayed in the mapView when running the iPhone simulator. I'd like to simulate that user is "moving" each 1 sec, how could I do that?

谢谢!

推荐答案

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

Looping through all the locations all at once with a sleep at each iteration won't work because the UI will be blocked until the method the loop is in finishes.

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

Instead, schedule the moveUser method to be called individually for each location so that the UI is not blocked throughout the sequence. The scheduling can be done using an NSTimer or possibly something simpler and more flexible such as the performSelector:withObject:afterDelay: method.

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

Keep an index ivar to keep track of which location to move to each time moveUser is called.

例如:

//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:方法不必更改。



请注意,如果不是删除,可以简化用户体验和代码并且每次都添加注释,在开头添加一次,只需在每次移动时更改其坐标属性。

这篇关于试图在MapView中模拟路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 07:39