从 KML 文件添加注释到 MKMapView

Adding annotations from a KML file to an MKMapView

我正在尝试将数据从 KML 文件加载到 MKMapView。我能够将数据解析为一个数组,现在我正尝试在地图上为每个项目创建注释。

使用下面的代码,我能够在地图上创建注释,但位置不正确:

Parser *parser = [[Parser alloc] initWithContentsOfURL:url];
parser.rowName = @"Placemark";
parser.elementNames = @[@"name", @"address", @"coordinates", @"description"];
[parser parse];

//parseItem is an array returned with all data after items are parsed.
for (NSDictionary *locationDetails in parser.parseItems) {
    MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
    annotation.title = locationDetails[@"name"];
    NSArray *coordinates = [locationDetails[@"coordinates"] componentsSeparatedByString:@","];
    annotation.coordinate = CLLocationCoordinate2DMake([coordinates[0] floatValue], [coordinates[1] floatValue]);

    [self.mapView addAnnotation:annotation];

}

坐标的NSLog结果为:

coords=-73.96300100000001,40.682846,0

所以看起来坐标是按经度、纬度顺序排列的,但 CLLocationCoordinate2DMake 函数采用纬度、经度。

除非坐标应该位于南极洲而不是纽约市,否则请尝试:

annotation.coordinate = CLLocationCoordinate2DMake(
                           [coordinates[1] doubleValue], 
                           [coordinates[0] doubleValue]);


另请注意,您应该将 floatValue 更改为 doubleValue 以获得更准确的位置(它还将匹配 CLLocationDegrees 的类型,它是 double 的同义词)。