2016-02-03 137 views
2
let latitude:CLLocationDegrees = 76.0100 
let longitude:CLLocationDegrees =25.3620 


let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) 

let latDelta:CLLocationDegrees = 1 
let lonDelta:CLLocationDegrees = 1 
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) 

let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) 

mapView.setRegion(region, animated: true) 

let annotation:MKPointAnnotation = MKPointAnnotation() 
    annotation.coordinate = location 
    annotation.title = "Office ." 
    annotation.subtitle = "My Office" 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 


    print("Locations = \(locations)") 

    let userLocation: CLLocation = locations[0] as CLLocation 

    //var latitude:CLLocationDegrees = userLocation.coordinate 
    //var longitude:CLLocationDegrees = -121.934048 
    //var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) 

    let latDelta:CLLocationDegrees = 0.01 
    let lonDelta:CLLocationDegrees = 0.01 
    let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) 

    let region:MKCoordinateRegion = MKCoordinateRegionMake(userLocation.coordinate, span) 

    mapView.setRegion(region, animated: true) 

我爲一個位置創建了一個註釋。現在我需要爲另一個位置創建一個註釋並將其顯示在地圖中。我怎樣才能表明這一點?如何使用swift ios在mapview中添加兩個註釋?

回答

4

創建一個自定義類爲 「MyAnnotation

import UIKit 
import MapKit 

class MyAnnotation: NSObject,MKAnnotation { 

    var title : String? 
var subTit : String? 
var coordinate : CLLocationCoordinate2D 

init(title:String,coordinate : CLLocationCoordinate2D,subtitle:String){ 

    self.title = title; 
    self.coordinate = coordinate; 
    self.subTit = subtitle; 

} 

} 

添加下面的代碼在你viewDidLoad中的視圖 - 控制: -

let latitude:CLLocationDegrees = 76.0100 
     let longitude:CLLocationDegrees = 25.3620 

     let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) 

     //Second Location lat and long 
     let latitudeSec:CLLocationDegrees = 75.0100 
     let longitudeSec:CLLocationDegrees = 24.3620 

     let locationSec:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitudeSec, longitudeSec) 

     let span:MKCoordinateSpan = MKCoordinateSpanMake(1, 1) 

     let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) 

     mapView.setRegion(region, animated: true) 


     let myAn1 = MyAnnotation(title: "Office", coordinate: location, subtitle: "MyOffice"); 

     let myAn2 = MyAnnotation(title: "Office 1", coordinate: locationSec, subtitle: "MyOffice 1"); 

     mapView.addAnnotation(myAn1); 
     mapView.addAnnotation(myAn2); 
     //Instead of writing two lines of annotation we can use addAnnotations() to add. 

取而代之的是你可以用for循環做的還。

Output of code

希望這會幫助你。

+0

我不明白。你能否給我提供完整的代碼? @ Er.Shreyansh沙。由於我是新手,很難理解代碼。 –

+0

給我5-10分鐘..我會更新我的答案。 –

+0

非常感謝。@ Er.Shrayansh Shah –