Create a title for annotation from MKLocalSearch

北城以北 提交于 2020-01-03 03:28:04

问题


I have added an MKLocalSearch and the pins are displaying correctly. The only problem is that the pins titles have both the name and address, were I only want the name. How would I change this. Here is the code I am using -

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{

    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
    request.naturalLanguageQuery = @"School";
    request.region = mapView.region;

    MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
    [localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {

        NSMutableArray *annotations = [NSMutableArray array];

        [response.mapItems enumerateObjectsUsingBlock:^(MKMapItem *item, NSUInteger idx, BOOL *stop) {

            // if we already have an annotation for this MKMapItem,
            // just return because you don't have to add it again

            for (id<MKAnnotation>annotation in mapView.annotations)
            {
                if (annotation.coordinate.latitude == item.placemark.coordinate.latitude &&
                    annotation.coordinate.longitude == item.placemark.coordinate.longitude)
                {
                    return;
                }
            }

            // otherwise, add it to our list of new annotations
            // ideally, I'd suggest a custom annotation or MKPinAnnotation, but I want to keep this example simple
            [annotations addObject:item.placemark];
        }];

        [mapView addAnnotations:annotations];
    }];
} 

回答1:


Since the title of the item.placemark cannot be directly modified, you'll need to create a custom annotation or MKPointAnnotation using the values from item.placemark.

(The comment in the code above the addObject line mentions an "MKPinAnnotation" but I think it was meant to say "MKPointAnnotation".)

The example below uses the simple option of using the pre-defined MKPointAnnotation class provided by the SDK for creating your own, simple annotations.

Replace this line:

[annotations addObject:item.placemark];

with these:

MKPlacemark *pm = item.placemark;

MKPointAnnotation *ann = [[MKPointAnnotation alloc] init];
ann.coordinate = pm.coordinate;
ann.title = pm.name;    //or whatever you want
//ann.subtitle = @"optional subtitle here";

[annotations addObject:ann];


来源:https://stackoverflow.com/questions/21617414/create-a-title-for-annotation-from-mklocalsearch

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