2015-01-15 23 views
1
  • 我是新来的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) 
        } 
    } 
    

感谢

回答

0

我假设你的视图控制器是如何在designed.When用户点击“查找位置”按钮,我们将通过用户输入的文字转换成地址并在地图上放置注释。 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)) 
} 
}) 
} 
} 
相关问题