11

我有一组可以很快更新的注释数据。目前,我删除了所有注释,然后将它们重新绘制回地图上。

NSArray *existingpoints = [mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"!(self isKindOfClass: %@)", [MKUserLocation class]]];
[mapView removeAnnotations:existingpoints];

我计算它们在自定义对象中的位置,因此希望能够调用它并“移动”注释,而无需删除并将其重新添加回地图。我所做的示例调用有效并且我想几乎“投票”如下。

- (CLLocationCoordinate2D) coordinate
{
    CLLocationCoordinate2D coord;
    coord.latitude = [lat doubleValue];
    coord.longitude = [lon doubleValue];


        double differencetime = exampleTime;
        double speedmoving;
        double distanceTravelled = speedmoving * differencetime;

        CLLocationDistance movedDistance = distanceTravelled;
        double radiansHeaded = DEG2RAD([self.heading doubleValue]);
        CLLocation *newLocation = [passedLocation newLoc:movedDistance along:radiansHeaded];
        coord = newLocation.coordinate;

    return coord;
}

根据要求,对象的 .h 文件,我没有 SetCoordinate 方法..

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface TestObject : NSObject <MKAnnotation>{
    NSString *adshex;
    NSString *lat;
    NSString *lon;


    NSString *title;
    NSString *subtitle;


    CLLocationCoordinate2D coordinate;
}
@property(nonatomic,retain)NSString *adshex;
@property(nonatomic,retain)NSString *lat;
@property(nonatomic,retain)NSString *lon;


@property(nonatomic,retain)NSString *title;
@property(nonatomic,retain)NSString *subtitle;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;


- (CLLocationCoordinate2D) coordinate;

@end
4

1 回答 1

21

如果您使用 setCoordinate 方法(或等效方法)更新注解的坐标,地图视图将自动更新注解在视图上的位置。 文档中的这个页面说明了以下内容:

重要提示:当您在类中实现坐标属性时,建议您综合其创建。如果您选择自己实现该属性的方法,或者如果您在将注释添加到映射后手动修改类的其他部分中该属性的基础变量,请务必发送键值观​​察 (KVO)当你这样做的通知。Map Kit 使用 KVO 通知来检测注释的坐标、标题和副标题属性的更改,并对地图显示进行任何需要的更改。如果您不发送 KVO 通知,您的注释位置可能无法在地图上正确更新。

只有在被告知(通过 KVO)坐标已更改时,地图视图才会知道重新读取注释的坐标属性。一种方法是实现一个 setCoordinate 方法,并在有更新注解位置的代码的任何地方调用它。

在您的代码中,您正在重新计算只读坐标属性本身的坐标。您可以做的是将其添加到注释 .m 文件(和 .h)中:

- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate
{
    //do nothing
}

在你更新位置的地方,调用注解上的 setCoordinate 方法:

[someAnnotation setCoordinate:someAnnotation.coordinate];

您可以在当前删除/重新添加注释的地方执行此操作。

上面的调用看起来很有趣,因为您在坐标获取器方法中重新计算了坐标。虽然它应该可以作为快速修复/测试,但我不建议经常使用它。

相反,您可以重新计算注释在外部的位置(您当前删除/重新添加注释的位置)并将新坐标传递给 setCoordinate。您的注释对象可以将其新位置存储在您当前拥有的 lat/lng ivars 中(将它们设置在 setCoordinate 中并仅使用那些来构造 CLLocationCoordinate2D 以从 getter 返回)或(更好)使用坐标 ivar 本身(将其设置为setCoordinate 并在 getter 中返回)。

于 2010-11-06T16:11:19.527 回答