如何使用swift ios在mapview中添加两个注释?
我已经为一个位置创建了一个注释。现在,我需要为另一个位置再创建一个注释,并在地图中显示它。如何显示它?将自定义类创建为“MyAnnotation” 在viewcontroller的视图加载中添加以下代码:-如何使用swift ios在mapview中添加两个注释?,ios,swift,mkmapview,Ios,Swift,Mkmapview,我已经为一个位置创建了一个注释。现在,我需要为另一个位置再创建一个注释,并在地图中显示它。如何显示它?将自定义类创建为“MyAnnotation” 在viewcontroller的视图加载中添加以下代码:- import UIKit import MapKit class MyAnnotation: NSObject,MKAnnotation { var title : String? var subTit : String? var coordinate : CLLocationC
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;
}
}
相反,您也可以使用for循环
希望这将对您有所帮助。无需自定义类。只需在位置之间循环,即可为每个位置创建注释。 假设地点为CLLocations,城市名称为cityNames,myMap为地图(UI)
我不明白。你能给我完整的代码吗@呃,沙。由于我是swift的新手,我在理解代码方面遇到了困难。非常感谢@呃,什里扬斯Shah@RakeshMohan:-Accept和+1,如果上面的答案对您有效。我使用了上面提供的相同代码,但它仍然只显示一个注释。亲爱的。。对地图视图进行缩放/移动。在模拟中,使用cmd+altr键缩放/缩放
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;
}
}
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.
var counter = 0
var allLocations = [MKPointAnnotation]()
for location in Locations {
let loc = MKPointAnnotation()
loc.title = cityNames[counter]
loc.subtitle = String(counter + 1)
loc.coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude);
allLocations.append(loc)
counter += 1
}
// show annotations
myMap.addAnnotations(allLocations as [MKAnnotation])
myMap.showAnnotations(myMap.annotations, animated: true)