最近接触到iOS 的mapkit,大概弄了一下,初学者,第一篇博客,还请各位多多指点。
下面是简单的实现,希望对各位有帮助
首先是storyboard
右边蓝色view继承MKMapView。
具体实现:
ViewController.swift
import UIKit
import MapKit
class ViewController: UIViewController {
var mapData:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
@IBOutlet weak var textSearch: UITextField!
@IBAction func submitClicked(sender: UIButton) {
mapData=MapHelper.geoCodeUsingAddress(textSearch.text)
self.performSegueWithIdentifier("showMap", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//界面跳转传值
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showMap" {
if let a = segue.destinationViewController as? mapKitViewController {
a.city=textSearch.text
a.latitude=mapData.latitude
a.longitude=mapData.longitude
}
}
}
}
import UIKit
import MapKit
class mapKitViewController: UIViewController , MKMapViewDelegate{
var city=String()
var latitude=Double()
var longitude=Double()
@IBOutlet var mapview: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let location=CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let span=MKCoordinateSpanMake(1, 1) //可以改变地图显示的比例
let region=MKCoordinateRegion(center: location, span: span)
mapview.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate=location
annotation.title=city
annotation.subtitle="China"
mapview.addAnnotation(annotation)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import Foundation
import MapKit
class MapHelper{
static func geoCodeUsingAddress(address:String) ->CLLocationCoordinate2D{
var latitude = 0.0
var longitude = 0.0
let esc_addr = address
let req = "http://maps.google.cn/maps/api/geocode/json?sensor=false&address=\(address)"
let result:NSString? = NSString(contentsOfURL: NSURL(string: req)!, encoding: NSUTF8StringEncoding, error: nil)
if let value=result{
let scanner:NSScanner = NSScanner(string: value as String)
if(scanner.scanUpToString("\"location\" :", intoString: nil) && scanner.scanString("\"location\" :", intoString: nil)){
if(scanner.scanUpToString("\"lat\" :", intoString: nil) && scanner.scanString("\"lat\" :", intoString: nil)){
scanner.scanDouble(&latitude)
}
if(scanner.scanUpToString("\"lng\" :", intoString: nil) && scanner.scanString("\"lng\" :", intoString: nil)){
scanner.scanDouble(&longitude)
}
}
}
var center:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0);
center.latitude = latitude;
center.longitude = longitude;
return center;
}
}
运行结果: