在MapView中搜索注释

时间:2016-11-11 00:54:26

标签: ios iphone swift annotations mkmapview

关于在annotations中搜索mapView,我跟踪了how-to-search-for-location-using-apples-mapkit 并用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)
    }
}

LocalSearchTable.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)
    }
}

2 个答案:

答案 0 :(得分:2)

您只需参考此链接即可 http://www.coderzheaven.com/2016/02/14/mapkit-demo-swift-annotation-custom-annotation-custom-annotation-with-button-search-showing-directions-apple-maps-ios/

您将了解以下主题

  • 在地图中显示注释。
  • 在地图中显示自定义注释。
  • 在地图中使用自定义按钮显示自定义注释。

答案 1 :(得分:0)

TL; DR

示例项目:https://github.com/JakubMazur/SO40539590

好的,所以一开始我会建议您从控制器代码中分离数据。我选择json格式作为最普遍的格式。所以:

[
   {
      "title":"Litzman Bar",
      "subtitle":"נמל תל אביב 18,תל אביב",
      "coordinates":{
         "lat":32.100668,
         "lon":34.775192
      }
   },
   {
      "title":"Shalvata",
      "subtitle":"האנגר 28,נמל תל אביב",
      "coordinates":{
         "lat":32.101145,
         "lon":34.775163
      }
   },
   {
      "title":"Markid",
      "subtitle":"אבן גבירול 30,תל אביב",
      "coordinates":{
         "lat":32.074961,
         "lon":34.781679
      }
   }
]

这基本上就是你的数据库。

现在让我们将其解析为Array,以便在ViewConttroller内使用。我再次建议您将其拆分为LocationCoordinate等模型对象。让我们看一下它的一个例子:

class Location: NSObject {

    var title : String = String()
    var subtitle : String = String()
    var coordinates : Coordinate = Coordinate()

    public class func locationFromDictionary(_ dictionary : Dictionary<String, AnyObject>) -> Location {
        let location : Location = Location()
        location.title = dictionary["title"] as! String
        location.subtitle = dictionary["subtitle"] as! String
        location.coordinates = Coordinate.coordinateFromDictionary(dictionary["coordinates"] as! Dictionary<String, AnyObject>)
        return location;
    }
}

我不会将用于解析json文件的代码粘贴到此对象,因为这不是这个问题的关键所在。您将在存储库中找到。

现在让我们关注问题。

我建议您不要搜索注释,而是搜索数据模型并在需要时重新绘制注释

为了做到这一点(我会使用UISearchBar):

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    self.displayArray = self.locationsDatabase.filter() {
        return $0.title.contains("i")
    }

然后当你像这样设置一个setter:

var displayArray : Array<Location> = [] {
    didSet {
        self.mapView .removeAnnotations(self.mapView.annotations)
        for location in displayArray {
            let coords : Coordinate = location.coordinates
            let point = MKPointAnnotation()
            point.coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(coords.latitude),CLLocationDegrees(coords.longitude))
            point.title = location.title
            point.subtitle = location.subtitle
            mapView.addAnnotation(point)
        }
    }
}

您可以重新绘制注释。边缘情况如空搜索字段,案例敏感,解雇键盘我留给你。但希望你能得到一般的想法。您可能认为它过度设计,但将对象作为单独的类和通用格式作为数据输入可能会在将来受益。

完整项目:https://github.com/JakubMazur/SO40539590