将位置存储为字符串,从字符串返回位置以在地图上显示。 iOS版

时间:2013-07-03 00:19:46

标签: iphone ios objective-c core-location

限制是我只能将位置信息存储为字符串 我希望使用coreLocation获取当前位置,然后将其转换为字符串,以便将其存储在数据库中。稍后,我希望从数据库中获取位置信息(字符串格式)并在地图上显示该位置。那么我该如何实现呢?我需要将哪些coreLocation信息存储为字符串?只有纬度和经度就足够了吗?那么我如何使用字符串来构建coreLocation,以便我可以在地图上显示它?谢谢!

2 个答案:

答案 0 :(得分:1)

如果您对CoreLocation数据的最终使用是针对地图应用程序的,那么纬度和经度就足够了。

使用NSValueTransformer,如下:

@interface CLLocationToStringTransformer : NSValueTransformer 
@end

@implementation CLLocationToStringTransformer

+ (BOOL) allowsReverseTransformation 
{ return YES; }

+ (Class) transformedValueClass
{ return [NSString class]; }

- (id) transformedValue: (id) value 
{ CLLocation *location = (CLLocation *) value;
  return [NSString stringWithFormat: "%@ %@",
                   theLocation.coordinate.latitude,
                   theLocation.coordinate.longitude]; } 

- (id)reverseTransformedValue:(id)value 
{ NSString *string = (NSString *) value;
  NSArray  *parts  = [string componentsSeparatedByString: @" "];
  return [[CLLocation alloc] initWithLatitude: [parts[0] doubleValue]
                                    longitude: [parts[1] doubleValue]]; }
@end

答案 1 :(得分:1)

是的,保存纬度/经度是关键。如果你尝试保存一个地址字符串,那么以后很容易将其重新绘制到地图上。

你可以用纬度后跟逗号然后是经度制作一个单独的字符串。当您稍后从数据库中获取此字符串时,只需用逗号分隔字符串即可。然后,您可以使用这些值作为纬度和经度来创建CLLocation对象或您需要的任何对象(MKAnnotation?)...

希望有所帮助。