我知道这个问题已经超过1年了,但我找不到任何解决方案,所以我希望我的解决方案将会有用。
您可以使用iOS-KML-Framework将KML加载到GMSMapView中。我是移植使用KML-Viewer
Add方法根据给定的URL解析KML从项目的代码,请确保您传递正确的应用程式束dispatch_queue_create():
- (void)loadKMLAtURL:(NSURL *)url
{
dispatch_queue_t loadKmlQueue = dispatch_queue_create("com.example.app.kmlqueue", NULL);
dispatch_async(loadKmlQueue, ^{
KMLRoot *newKml = [KMLParser parseKMLAtURL:url];
[self performSelectorOnMainThread:@selector(kmlLoaded:) withObject:newKml waitUntilDone:YES];
});
}
处理的KML解析导致或错误:
- (void)kmlLoaded:(id)sender {
self.navigationController.view.userInteractionEnabled = NO;
__kml = sender;
// remove KML format error observer
[[NSNotificationCenter defaultCenter] removeObserver:self name:kKMLInvalidKMLFormatNotification object:nil];
if (__kml) {
__geometries = __kml.geometries;
dispatch_async(dispatch_get_main_queue(), ^{
self.navigationController.view.userInteractionEnabled = YES;
[self reloadMapView];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
self.navigationController.view.userInteractionEnabled = YES;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil)
message:NSLocalizedString(@"Failed to read the KML file", nil)
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", nil)
otherButtonTitles:nil];
[alertView show];
});
}
}
走了过来,从KML几何形状的物品,并将它们添加到GMSMapView中作为标记:
- (void)reloadMapView
{
NSMutableArray *annotations = [NSMutableArray array];
for (KMLAbstractGeometry *geometry in __geometries) {
MKShape *mkShape = [geometry mapkitShape];
if (mkShape) {
if ([mkShape isKindOfClass:[MKPointAnnotation class]]) {
MKPointAnnotation *annotation = (MKPointAnnotation*)mkShape;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = annotation.coordinate;
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.icon = [UIImage imageNamed:@"marker"];
marker.title = annotation.title;
marker.userData = [NSString stringWithFormat:@"%@", geometry.placemark.descriptionValue];
marker.map = self.mapView;
[annotations addObject:annotation];
}
}
}
// set bounds in next run loop.
dispatch_async(dispatch_get_main_queue(), ^{
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] init];
for (id <MKAnnotation> annotation in annotations)
{
bounds = [bounds includingCoordinate:annotation.coordinate];
}
GMSCameraUpdate *update = [GMSCameraUpdate fitBounds:bounds];
[self.mapView moveCamera:update];
[self.mapView animateToViewingAngle:50];
});
}
在最后一个方法结束时,我们使用updating the camera view来适应添加到地图上的所有标记。如果不需要,可以移除这部分。
你似乎做了很多更多的传递到主线程比严格要求... – Wain
@Wain,你可能是对的。原来的代码不是我的,所以我没有机会审查它的效率。刚刚将它移植到Google Maps SDK昨天。 – f0xik