iOS開(kāi)發(fā) - MapKit框架之大頭針及當(dāng)前位置

創(chuàng)建大頭針、增加標(biāo)記及覆蓋物

步驟-SB拖入地圖視圖-然后如下

1.png
import MapKit

class MapViewController: UIViewController,MKMapViewDelegate {
    
    @IBOutlet weak var mapView: MKMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView.delegate = self

        //創(chuàng)建大頭針
        let center =  CLLocationCoordinate2DMake(23.114155, 113.318977)
        let span = MKCoordinateSpanMake(0.2, 0.2)
        self.mapView.region = MKCoordinateRegionMake(center, span)
        //向地址增加標(biāo)記
        let annotation = MKPointAnnotation()
        annotation.coordinate = center
        annotation.title = "當(dāng)前大約位置"
        annotation.subtitle = ""
        self.mapView.addAnnotation(annotation)
        //創(chuàng)建一個(gè)新的圓形覆蓋物
        let overlay = MKCircle(centerCoordinate: center, radius: 5000)
        self.mapView.addOverlay(overlay)
    }

    //自定義大頭針樣式,默認(rèn)是紅色
    //func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? 
    //覆蓋物的委托方法
    func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
        
        let circleRenderer = MKCircleRenderer(overlay: overlay)
        circleRenderer.strokeColor = UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 0.5)
        circleRenderer.fillColor = UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 0.5)
        return circleRenderer
    }
}

當(dāng)前位置實(shí)時(shí)顯示

2.png
import MapKit

class MapViewController: UIViewController,MKMapViewDelegate {
    
    @IBOutlet weak var mapView: MKMapView!
    
    var spanState = true 

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView.delegate = self
        self.mapView.showsUserLocation = true
    }
    
    func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
        let coord = userLocation.coordinate
        let center = CLLocationCoordinate2DMake(coord.latitude, coord.longitude)
        print(center)
        
        if spanState == true { //首次時(shí)候的縮放范圍
            let span = MKCoordinateSpanMake(0.01, 0.01)
            self.mapView.region = MKCoordinateRegionMake(center, span)
            spanState = !spanState
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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