MapView添加自定義大頭針(Obj-C)

1.創(chuàng)建大頭針模型類,遵循<MKMapViewDelegate>協(xié)議

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface JSAnnotation : NSObject  <MKAnnotation>
//經(jīng)緯度
@property (nonatomic) CLLocationCoordinate2D coordinate;
//標(biāo)題
@property (nonatomic, copy, nullable) NSString *title;
//子標(biāo)題
@property (nonatomic, copy, nullable) NSString *subtitle;
@end

2.獲取屏幕坐標(biāo)
3.創(chuàng)建自定義大頭針模型對象
4.設(shè)置大頭針模型信息
5.將自定義大頭針添加到MapView中

示例代碼:

// 添加大頭針到點(diǎn)擊的位置
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    // 獲取touch
    UITouch *touch = touches.anyObject;
    
    // 獲取點(diǎn)擊屏幕坐標(biāo)
    CGPoint point = [touch locationInView:touch.view];
    
    // 地圖添加大頭針模型類,生成模型對象  所有遵守MKAnnotation協(xié)議的對象都可以作為大頭針的模型
    //創(chuàng)建自定義大頭針模型對象
    JSAnnotation *annotation = [[JSAnnotation alloc]init];
    
    
    // 設(shè)置數(shù)據(jù) (mapView可以對iOS坐標(biāo)和經(jīng)緯度進(jìn)行轉(zhuǎn)化)
    annotation.coordinate = [self.mapView convertPoint:point toCoordinateFromView:touch.view];
    annotation.title = @"自定義大頭針";
    annotation.subtitle = @"系統(tǒng)樣式";
    
    // mapView中添加大頭針
    [self.mapView addAnnotation:annotation];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容