Objective c 从NSArray坐标在MKMapView上添加MKAnnotations
我需要在MKMapView上添加几个注释(例如,一个国家的每个城市都有一个注释),我不想用所有城市的纬度和经度初始化每个CLLocation2D。我认为使用数组是可能的,所以这是我的代码:Objective c 从NSArray坐标在MKMapView上添加MKAnnotations,objective-c,nsarray,mkmapview,Objective C,Nsarray,Mkmapview,我需要在MKMapView上添加几个注释(例如,一个国家的每个城市都有一个注释),我不想用所有城市的纬度和经度初始化每个CLLocation2D。我认为使用数组是可能的,所以这是我的代码: NSArray *latit = [[NSArray alloc] initWithObjects:@"20", nil]; // <--- I cannot add more than ONE object NSArray *longit = [[NSArray alloc] initWithObje
NSArray *latit = [[NSArray alloc] initWithObjects:@"20", nil]; // <--- I cannot add more than ONE object
NSArray *longit = [[NSArray alloc] initWithObjects:@"20", nil]; // <--- I cannot add more than ONE object
// I want to avoid code like location1.latitude, location2.latitude,... locationN.latitude...
CLLocationCoordinate2D location;
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
for (int i=0; i<[latit count]; i++) {
double lat = [[latit objectAtIndex:i] doubleValue];
double lon = [[longit objectAtIndex:i] doubleValue];
location.latitude = lat;
location.longitude = lon;
annotation.coordinate = location;
[map addAnnotation: annotation];
}
NSArray*latit=[[NSArray alloc]initWithObjects:@“20”,nil];// 始终使用相同的注释对象,即:
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
在for循环中置换它,或在添加到贴图之前复制它
解释:这是在MKAnnotation
协议中找到的注释属性:
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
正如您所看到的,它没有复制对象,因此,如果始终添加相同的注释,则会有重复的注释。如果在时间1添加坐标为(20,20)的注释,则在时间2将注释坐标更改为(40,40)并将其添加到地图中,但它是同一对象
此外,我不建议将NSNumber
对象放入其中。相反,制作一个唯一的数组并填充对象,因为它们是用来存储坐标的。CLLocation
类具有以下属性:
@property(readonly, NS_NONATOMIC_IPHONEONLY) CLLocationCoordinate2D;
它也是一个不可变的对象,因此您需要在创建对象时初始化此属性。使用initWithLatitude:经度:方法:
- (id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude;
以便编写更好的代码版本:
#define MakeLocation(lat,lon) [[CLLocation alloc]initWithLatitude: lat longitude: lon];
NSArray* locations= @[ MakeLocation(20,20) , MakeLocation(40,40) , MakeLocation(60,60) ];
for (int i=0; i<[locations count]; i++) {
MKPointAnnotation* annotation= [MKPointAnnotation new];
annotation.coordinate= [locations[i] coordinate];
[map addAnnotation: annotation];
}
#定义MakeLocation(纬度,经度)[[CLLocation alloc]initWithLatitude:lat经度:lon];
NSArray*locations=@[MakeLocation(20,20)、MakeLocation(40,40)、MakeLocation(60,60)];
对于(inti=0;我非常优雅,解释也很好。我只需要添加CoreLocation框架,您的代码就完美了。谢谢!