我试图将MKAnnotationView
添加到MKMapView
,但我无法做到......有人可以帮助我吗?
这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
var latitude:CLLocationDegrees = locationManager.location.coordinate.latitude
var longitude:CLLocationDegrees = locationManager.location.coordinate.longitude
var homeLati: CLLocationDegrees = 40.01540192
var homeLong: CLLocationDegrees = 20.87901079
var latDelta:CLLocationDegrees = 0.01
var longDelta:CLLocationDegrees = 0.01
var theSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var myHome:CLLocationCoordinate2D = CLLocationCoordinate2DMake(homeLati, homeLong)
var myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
var theRegion:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, theSpan)
self.theMapView.setRegion(theRegion, animated: true)
self.theMapView.mapType = MKMapType.Hybrid
self.theMapView.showsUserLocation = true
///Red Pin
var myHomePin = MKPointAnnotation()
myHomePin.coordinate = myHome
myHomePin.title = "Home"
myHomePin.subtitle = "Bogdan's home"
self.theMapView.addAnnotation(myHomePin)
var anView:MKAnnotationView = MKAnnotationView()
anView.annotation = myHomePin
anView.image = UIImage(named:"xaxas")
anView.canShowCallout = true
anView.enabled = true
}
答案 0 :(得分:36)
您需要实施viewForAnnotation
委托方法并从那里返回MKAnnotationView
。
以下是一个例子:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if (annotation is MKUserLocation) {
//if annotation is not an MKPointAnnotation (eg. MKUserLocation),
//return nil so map draws default view for it (eg. blue dot)...
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.image = UIImage(named:"xaxas")
anView.canShowCallout = true
}
else {
//we are re-using a view, update its annotation reference...
anView.annotation = annotation
}
return anView
}
请记住,当您想要使用自己的自定义图像时,需要创建 plain MKAnnotationView
。 MKPinAnnotationView
只能用于标准引脚注释。
另请注意,在致电locationManager.location
后,您不应立即尝试访问startUpdatingLocation
。它可能尚未准备好。
使用didUpdateLocations
委托方法。
您还需要致电requestAlwaysAuthorization
/ requestWhenInUseAuthorization
(请参阅Location Services not working in iOS 8)。
答案 1 :(得分:0)
1-您的地图视图应将自己委托给您的视图控制器 2-你应该实现
func mapView(aMapView: MKMapView!, viewForAnnotation annotation: CustomMapPinAnnotation!) -> MKAnnotationView!
从添加到地图
的每个注释中调用此函数3-对注释进行子类化以在viewForAnnotation方法中识别它们
4-在viewForAnnotation中,添加
if annotation.isKindOfClass(CustomMapPinAnnotation)
{
// change the image here
var pinView = aMapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? YourSubclassedAnnotation
pinView!.image = UIImage(contentsOfFile: "xyz")
}
答案 2 :(得分:0)
您必须显示注释,然后您必须添加show annotation方法:
annotation
MKPointAnnotation
是octave-config
的实例。