如何显示用户定义的位置

时间:2015-01-15 05:34:14

标签: ios swift mapkit

  • 我是swift的新手。
  • 当用户在文本字段中输入任何位置时,请指导我如何在地图上显示location
  • 使用此文本字段字符串如何在map上显示此位置。 这是我的代码

    import UIKit
    import CoreLocation
    import MapKit
    class DetailViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
    
    var manager:CLLocationManager!
    var myLocations: [CLLocation] = []
    
    
    required init(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    //Setup our Location Manager
        manager = CLLocationManager()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()
        //Setup our Map View
        theMap.delegate = self
        theMap.mapType = MKMapType.Satellite
        theMap.showsUserLocation = true
    
    }
    func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
        theLabel.text = "\(locations[0])"
        myLocations.append(locations[0] as CLLocation)
    
        let spanX = 0.007
        let spanY = 0.007
        var newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
        theMap.setRegion(newRegion, animated: true)
        if (myLocations.count > 1){
            var sourceIndex = myLocations.count - 1
            var destinationIndex = myLocations.count - 2
            let c1 = myLocations[sourceIndex].coordinate
            let c2 = myLocations[destinationIndex].coordinate
            var a = [c1, c2]
            var polyline = MKPolyline(coordinates: &a, count: a.count)
            theMap.addOverlay(polyline)
        }
    }
    

感谢

1 个答案:

答案 0 :(得分:0)

我假设您的视图控制器是如何设计的。当用户点击"查找位置"按钮我们将用户输入的文本转换为地址并在地图上放置注释。 enter image description here

@IBOutlet var userinput: UITextField!
@IBAction func findlocation(sender: AnyObject) {
if(userinput.text == "")
 {
 //location cannot be empty.Show an alert to notify user
 }
 else
 {
  var address:String = userinput.text as String // 1 Infinite Loop, CA, USA
 var geocoder = CLGeocoder()
 geocoder.geocodeAddressString(address, {(placemarks: [AnyObject]!, error: NSError!) -> Void in
 if let placemark = placemarks?[0] as? CLPlacemark {
       self.mapView.addAnnotation(MKPlacemark(placemark: placemark))
 }
 })
 }
 }