ios - map 注释搜索

标签 ios iphone swift search mkmapview

我关注了一个 how-to-search-for-location-using-apples-mapkit关于在 mapView 中搜索 annotations 并使用 MKLocalSearch 在世界范围内进行搜索。

但是,我不想使用 MKLocalSearch 进行搜索,而是搜索我自己的 annotations 我自己添加的,例如:

let LitzmanLocation = CLLocationCoordinate2DMake(32.100668,34.775192)
        // Drop a pin
        let Litzman = MKPointAnnotation()
        Litzman.coordinate = LitzmanLocation
        Litzman.title = "Litzman Bar"
        Litzman.subtitle = "נמל תל אביב 18,תל אביב"
        mapView.addAnnotation(Litzman)

        let ShalvataLocation = CLLocationCoordinate2DMake(32.101145,34.775163)
        // Drop a pin
        let Shalvata = MKPointAnnotation()
        Shalvata.coordinate = ShalvataLocation
        Shalvata.title = "Shalvata"
        Shalvata.subtitle = "האנגר 28,נמל תל אביב"
        mapView.addAnnotation(Shalvata)


        let MarkidLocation = CLLocationCoordinate2DMake(32.074961,34.781679)
        // Drop a pin
        let Markid = MKPointAnnotation()
        Markid.coordinate = MarkidLocation
        Markid.title = "Markid"
        Markid.subtitle = "אבן גבירול 30,תל אביב"
        mapView.addAnnotation(Markid)

这是我的代码:

MapViewController.Swift:

import UIKit
import MapKit
import CoreLocation

protocol HandleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark)
}

class MapViewController: UIViewController,MKMapViewDelegate, CLLocationManagerDelegate,UISearchBarDelegate{


    @IBOutlet var mapView: MKMapView!

    var resultSearchController:UISearchController? = nil

    var selectedPin:MKPlacemark? = nil

    @IBAction func MapSearchController(sender: AnyObject) {
        resultSearchController!.hidesNavigationBarDuringPresentation = false
        self.resultSearchController!.searchBar.delegate = self
        presentViewController(resultSearchController!, animated: true, completion: nil)
        self.resultSearchController!.searchBar.barTintColor = UIColor.blackColor()
        self.resultSearchController!.searchBar.placeholder = "חפש ברים"
        self.resultSearchController!.dimsBackgroundDuringPresentation = true
        self.resultSearchController!.searchBar.sizeToFit()
    }
override func viewDidLoad() {
        super.viewDidLoad()

        let locationSearchTable = storyboard!.instantiateViewControllerWithIdentifier("LocationSearchTable") as! LocationSearchTable
        resultSearchController = UISearchController(searchResultsController: locationSearchTable)
        resultSearchController?.searchResultsUpdater = locationSearchTable

        locationSearchTable.mapView = mapView

        locationSearchTable.handleMapSearchDelegate = self
}
}
}

extension MapViewController: HandleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark){
        // cache the pin
        selectedPin = placemark
        // clear existing pins
        mapView.removeAnnotations(mapView.annotations)
        let annotation = MKPointAnnotation()
        annotation.coordinate = placemark.coordinate
        annotation.title = placemark.name
        if let city = placemark.locality,
            let state = placemark.administrativeArea {
            annotation.subtitle = "(city) (state)"
        }
        mapView.addAnnotation(annotation)
        let span = MKCoordinateSpanMake(0.05, 0.05)
        let region = MKCoordinateRegionMake(placemark.coordinate, span)
        mapView.setRegion(region, animated: true)
    }
}

本地搜索表.Swift:

import UIKit
import MapKit

class LocationSearchTable : UITableViewController {

    var matchingItems:[MKMapItem] = []
    var mapView: MKMapView? = nil

    var handleMapSearchDelegate:HandleMapSearch? = nil

    func parseAddress(selectedItem:MKPlacemark) -> String {
        // put a space between "4" and "Melrose Place"
        let firstSpace = (selectedItem.subThoroughfare != nil && selectedItem.thoroughfare != nil) ? " " : ""
        // put a comma between street and city/state
        let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) && (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : ""
        // put a space between "Washington" and "DC"
        let secondSpace = (selectedItem.subAdministrativeArea != nil && selectedItem.administrativeArea != nil) ? " " : ""
        let addressLine = String(
            format:"%@%@%@%@%@%@%@",
            // street number
            selectedItem.subThoroughfare ?? "",
            firstSpace,
            // street name
            selectedItem.thoroughfare ?? "",
            comma,
            // city
            selectedItem.locality ?? "",
            secondSpace,
            // state
            selectedItem.administrativeArea ?? ""
        )
        return addressLine
    }

    }

extension LocationSearchTable : UISearchResultsUpdating {
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        guard let mapView = mapView,
            let searchBarText = searchController.searchBar.text else { return }
        let request = MKLocalSearchRequest()
        request.naturalLanguageQuery = searchBarText
        request.region = mapView.region
        let search = MKLocalSearch(request: request)
        search.startWithCompletionHandler { response, _ in
            guard let response = response else {
                return
            }
            self.matchingItems = response.mapItems
            self.tableView.reloadData()
        }
    }

}

extension LocationSearchTable {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return matchingItems.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("MapSearchCell")!
        let selectedItem = matchingItems[indexPath.row].placemark
        cell.textLabel?.text = selectedItem.name
        cell.detailTextLabel?.text = parseAddress(selectedItem)
        return cell
    }
}

extension LocationSearchTable {
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let selectedItem = matchingItems[indexPath.row].placemark
        handleMapSearchDelegate?.dropPinZoomIn(selectedItem)
        dismissViewControllerAnimated(true, completion: nil)
    }
}

最佳答案

因此创建一个注释对象数组并将其保存在一个实例变量中。我们称它为 annotationsArray

然后您可以设计一个用户界面,让用户输入搜索词。假设您只搜索标题。然后你可以使用:

let titleMatches = annotationsArray.filter{$0.title == titleToMatch}

然后使用 addAnnotations() 函数将过滤后的注释集显示到 map 上。 (注意复数)

关于ios - map 注释搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620002/

相关文章:

ios - 在 XMPP 框架中在后台发送本地通知

ios - 在 Swift 中附加到字典数组

ios - 推送特定的viewController

ios - Swift 中选择器有返回值吗?

ios - RxDataSources 单元重新加载动画无法正常工作

ios - 如何实现左右滑动以在 swift IOS 中更改数据/ View ?

ios - 在 safari 或 native 应用程序中快速打开 3 个 URL

ios - 如何从 NSString 中捕获最后 4 个字符

iphone - 是否可以不关闭 UIAlertView

iphone - 如何使用 Quartz 和 CGLayers 在背景上绘制 Sprite ?