gpt4 book ai didi

iphone - map 套件 :How to add annotation on MKLocalSearch results placemarks?

转载 作者:行者123 更新时间:2023-11-29 13:15:10 24 4
gpt4 key购买 nike

基本上,我需要一种方法来对搜索请求提取的所有“沃尔玛”进行注释。我没有使用界面生成器,我只是为这个应用程序使用代码。

MKMapView * map = [[MKMapView alloc] initWithFrame:
CGRectMake(0, 0, 320, 480)];
map.delegate = self;
[self.view addSubview:map];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.



MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = @"Walmart";
request.region = map.region;

最佳答案

我建议在 viewDidLoad 中简单地创建 mapview:

- (void)viewDidLoad
{
[super viewDidLoad];

MKMapView * map = [[MKMapView alloc] initWithFrame:self.view.bounds];
map.delegate = self;

[self.view addSubview:map];
}

但是当用户移动 map 时,寻找沃尔玛并添加注释:

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
// if on slow network, it's useful to keep track of the previous
// search, and cancel it if it still exists

[self.previousSearch cancel];

// create new search request

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

// initiate new search

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];
}];

// update our "previous" search, so we can cancel it if necessary

self.previousSearch = localSearch;
}

很明显,此代码示例假定您对先前的搜索操作具有 weak 属性。 (严格来说,这不是必需的,但如果您在 Internet 连接速度较慢的情况下浏览 map 可能会给您带来更好的性能。)无论如何,该属性将定义如下:

@property (nonatomic, weak) MKLocalSearch *previousSearch;

还有其他可能的改进(例如 UIActivityIndi​​catorView 或网络事件指示器,如果搜索正在进行,可能会删除不在 map 当前区域内的注释等),但希望您明白了.

关于iphone - map 套件 :How to add annotation on MKLocalSearch results placemarks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16021870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com