在mapView

时间:2017-02-03 11:51:34

标签: ios uitableview search annotations mkmapview

在我的项目中,我有一个mapView,其中有很多annotations&我想在地图中添加搜索功能,以便我可以搜索annotations并快速找到我想要的注释。

我按照我在网络上找到的教程但是全局搜索(MKLocalSearch)而不是注释。

我试过寻找一个教程\帮助解决我的问题,但我现在很长时间都没有得到任何帮助。

我已经做了这些注释:

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:

    //All my Map code is here
    }
    }
    }
    extension MapViewController: HandleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark){
        // cache the pin
        selectedPin = placemark
        // clear existing pins
        let annotation = MKPointAnnotation()
        annotation.coordinate = placemark.coordinate
        annotation.title = placemark.name
        if let _ = placemark.locality,
            let _ = placemark.administrativeArea {
            annotation.subtitle = ""
        }
        mapView.addAnnotation(annotation)
        let span = MKCoordinateSpanMake(0.01, 0.01)
        let region = MKCoordinateRegionMake(placemark.coordinate, span)
        mapView.setRegion(region, animated: true)
    }  
}

SearchTable:

import UIKit
import MapKit

class LocationSearchTable : UITableViewController {

    var matchingItems = [CustomAnnotations]()
    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
    }

    func search(keywords:String) {
        self.matchingItems.removeAll()
        for annotation in self.mapView!.annotations {
            if annotation.isKindOfClass(CustomAnnotations) {
                //Just an example here for searching annotation by title, you could add other filtering actions else.
                if (annotation.title??.rangeOfString(keywords) != nil) {
                    self.matchingItems.append(annotation as! CustomAnnotations)
                }
            }
        }
        self.tableView.reloadData()
    }

}

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", forIndexPath: indexPath)
        let selectedItem = matchingItems[indexPath.row]
        cell.textLabel?.text = selectedItem.title
        cell.detailTextLabel?.text = selectedItem.subtitle
        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)
    }
}

我的问题是如何将其转换为仅搜索我的注释而不是使用MKLocalSearch搜索全世界。

我是使用2.3和Xcode 8的初学者编码器

感谢您的帮助。

答案中的错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

Swift 3 ,如果转换Swift版本不方便,请参考主要参考)

首先,定义一个从MKPointAnnotation继承的自定义类,用于区分您的注释:

class CustomedAnnottion: MKPointAnnotation{
    //You can also add some varible for saving custom data, like: var id:Int?
}

第二次,使用自定义注记类添加注释:

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

第三次,将搜索表视图数据源更改为:

var matchingItems = [CustomedAnnottion]()

第四(搜索自定义注释最重要),实现如下搜索功能:

func search(keywords:String) {
    self.matchingItems.removeAll()
    for annotation in self.mapView.annotations {
        if annotation.isKind(of: CustomedAnnottion.classForCoder()) {
            //Just an example here for searching annotation by title, you could add other filtering actions else.
            if (annotation.title??.range(of: keywords) != nil) {
                self.matchingItems.append(annotation as! CustomedAnnottion)
            }
        }
    }
    self.tableView.reloadData()
}

最后,将tableView的'cellForRowAtIndexPath'方法更改为:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MapSearchCell", for: indexPath)
    let selectedItem = matchingItems[indexPath.row]
    cell.textLabel?.text = selectedItem.title
    cell.detailTextLabel?.text = selectedItem.subtitle
    return cell
}

这些是实现您的要求的一般步骤,您可以随意更改任何代码以满足您的特定需求。