MapBox image for annotation from url

回眸只為那壹抹淺笑 提交于 2019-12-12 02:56:32

问题


I'm using MapBox, and right now, I'm experiencing next problem: I'm using MapBox's delegate method for implementing image for annotation. Now I have some annotation images that needs to be loaded from URL. Problem is that method for custom image is called before image is loaded from URL and there is not image shown on Map. This is code in method:

- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation
{
 MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:@"custom"];
NSURL *url = [NSURL URLWithString:@"http://www.fnordware.com/superpng/pnggrad16rgb.png"];

NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:@"customUrl"];
}

回答1:


Two ways to load network resources and use them as annotation images:

  1. Use a placeholder image and then update the annotation once the real image has loaded.

    Updating the image is supported in Mapbox iOS SDK v3.1.0+; previously this required removing and re-adding the annotation.

  2. Download the image before adding the annotation.

Additionally, the code you included does not check if the annotation image can be dequeued and reused — it always creates a new annotation image. The reuse pattern should look more like this:

- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation
{
    MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:@"customImage"];

    if ( ! annotationImage)
    {
        UIImage *image = [UIImage imageNamed:@"customImage"];
        annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:@"customImage"];
    }

    return annotationImage;
}


来源:https://stackoverflow.com/questions/35187940/mapbox-image-for-annotation-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!