MapView 使用

1 篇文章 / 0 new
author
MapView 使用
1. import MapKit;
2. 拉出參考 @IBOutlet weak var mapView: MKMapView!
3. 如何標示大頭針
//可利用定位 delegate 取得目前座標資訊
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //獲取最新的座標
    let currLocation:CLLocation = locations.last!
    //將map中心點定在目前所在的位置
    //span是地圖zoom in, zoom out的級距
    let nowLocation = CLLocationCoordinate2D(latitude: currLocation.coordinate.latitude, longitude: currLocation.coordinate.longitude);
    let _span:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.0005, longitudeDelta: 0.0005);
    self.mapView.setRegion(MKCoordinateRegion(center: nowLocation, span: _span), animated: true);
    //加入座標
    addPocintAnnotation(latitude: currLocation.coordinate.latitude, longitude: currLocation.coordinate.longitude);
}
//新增座標
var point:MKPointAnnotation? = nil;
func addPocintAnnotation(latitude:CLLocationDegrees , longitude:CLLocationDegrees){
    if(point != nil) {
        self.mapView.removeAnnotation(point!);
    }
    //大頭針
    point = MKPointAnnotation();
    //設定大頭針的座標位置
    point!.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude);
    point!.title = "I'm here";
    point!.subtitle = "緯度:\(latitude) 經度:\(longitude)";
 
    self.mapView.addAnnotation(point!);  
}
► 變更大頭丁顏色或套用自訂圖示
1. extend MKMapViewDelegate
2. 給定 delegate self.mapView.delegate = self;// call mapView
3. 實作 MKMapViewDelegate
//自訂大頭針
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    var pointView : MKPinAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: "CustomerPoint") as?MKPinAnnotationView;
    if(pointView == nil){
        pointView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "CustomerPoint");
        //因為已經改寫了Annotation View,所以要將canShowCallout改成true,否則點擊大頭針不會跑出來我們剛剛指定的title跟subtitle
        pointView?.canShowCallout = true;
        pointView!.pinTintColor = .green;
    }
    return pointView;
 
    //自定圖標
    /*if (annotation is MKUserLocation) {
        //如果 annotation 不是一個 MKPointAnnotation (eg. MKUserLocation), 則返回 nil
        return nil;
    }
    let reuseId = "test";
    var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId);
    if anView == nil {
        anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId);
        anView?.image = UIImage(named:"Home");
        anView?.canShowCallout = true;
    } else {
        anView?.annotation = annotation;
    }
    return anView;*/
}
Free Web Hosting