使用 MKLocalSearch 進行本地搜尋實現

MKLocalSearch 允許使用者使用健身房等自然語言字串搜尋位置。搜尋完成後,該類將返回指定區域內與搜尋字串匹配的位置列表。

搜尋結果是 MKLocalSearchResponse 物件中的 MKMapItem 形式。

讓我們嘗試一下

MKLocalSearchRequest *request = 
    [[MKLocalSearchRequest alloc] init];//initialising search request
request.naturalLanguageQuery = @”Gym”; // adding query
request.region = _mapView.region; //setting region
MKLocalSearch *search = 
     [[MKLocalSearch alloc]initWithRequest:request];//initiate search

[search startWithCompletionHandler:^(MKLocalSearchResponse 
     *response, NSError *error) 
{
   if (response.mapItems.count == 0)
       NSLog(@"No Matches");
   else
       for (MKMapItem *item in response.mapItems)
       {
           NSLog(@"name = %@", item.name);
           NSLog(@"Phone = %@", item.phoneNumber);
        }
}];