如何在Swift 3中的MapView上生成不同的引脚



我正在遇到一个问题,我尝试生成不同的图标以在位置的地图视图上显示。但是,我需要你们的帮助。到目前为止,我已经硬编码了一个销钉以在地图视图上显示。我还在资产中有不同的引脚,我想通过在MapView上生成它们来显示它们。如何生成不同的图标以从API上显示我的地图视图?谢谢您的帮助。

这是我的代码:

import UIKit
import MapKit
import CoreLocation
class MapViewController: BaseViewController{
    @IBOutlet weak var leadingConstraints: NSLayoutConstraint!
    @IBOutlet weak var menuView: UIView!
    @IBOutlet weak var mapView: MKMapView!
    fileprivate let locationManager = CLLocationManager()
    fileprivate var startedLoadingPOIs = false
    fileprivate var places = [Place]()
    fileprivate var arViewController: ARViewController!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    var nearMeIndexSelected = NearMeIndexTitle()
    var menuShowing = false
    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
        locationManager.requestWhenInUseAuthorization()
        //making shadow of our menu view
        menuView.layer.shadowOpacity = 1
        menuView.layer.shadowRadius = 7
    }
    @IBAction func showARController(_ sender: Any) {
        arViewController = ARViewController()
        arViewController.dataSource = self
        arViewController.maxVisibleAnnotations = 30
        arViewController.headingSmoothingFactor = 0.05
        arViewController.setAnnotations(places)
        self.navigationController!.pushViewController(arViewController, animated: true)
    }
}
extension MapViewController: CLLocationManagerDelegate, MKMapViewDelegate {
    //  // Changing the Pin Color on the map.
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            mapView.tintColor = #colorLiteral(red: 0.8823529412, green: 0.1647058824, blue: 0.1333333333, alpha: 1)
            return nil
        } else {
            let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
            let pin = mapView.view(for: annotation) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
            pin.image = UIImage(named: "pins")
            return pin
            return annotationView
        }
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if locations.count > 0 {
            let location = locations.last!
            print("Accuracy: (location.horizontalAccuracy)")
            if location.horizontalAccuracy < 100 {
                manager.stopUpdatingLocation()
                let span = MKCoordinateSpan(latitudeDelta: 0.013, longitudeDelta: 0.013)
                let region = MKCoordinateRegion(center: location.coordinate, span: span)
                mapView.region = region
                if !startedLoadingPOIs {
                    DispatchQueue.main.async {
                        self.activityIndicator.startAnimating()
                    }
                    startedLoadingPOIs = true
                    let loader = PlacesLoader()
                    loader.loadPOIS(location: location, radius: 1500) { placesDict, error in
                        if let dict = placesDict {
                            guard let placesArray = dict.object(forKey: "results") as? [NSDictionary] else { return }
                            for placeDict in placesArray {
                                let latitude = placeDict.value(forKeyPath: "geometry.location.lat") as! CLLocationDegrees
                                let longitude = placeDict.value(forKeyPath: "geometry.location.lng") as! CLLocationDegrees
                                let reference = placeDict.object(forKey: "reference") as! String
                                let name = placeDict.object(forKey: "name") as! String
                                let address = placeDict.object(forKey: "vicinity") as! String
                                let location = CLLocation(latitude: latitude, longitude: longitude)
                                let place = Place(location: location, reference: reference, name: name, address: address)
                                self.places.append(place)
                                let annotation = PlaceAnnotation(location: place.location!.coordinate, title: place.placeName)
                                DispatchQueue.main.async {
                                    self.mapView.addAnnotation(annotation)
                                }
                            }
                            DispatchQueue.main.async {
                                self.activityIndicator.stopAnimating()
                                self.mapView.isHidden = false
                            }
                        }
                    }
                }
            }
        }
    }
}

您可以比较注释的坐标并为该注释指定自定义PIN。

if annotation.coordinate == "Your Custom Pin Coordinate" { //set custom pin }

假设我想为所选的地方添加一个自定义别针。

var selectedPlace: PlaceAnnotation

在您的循环内。假设我选择的地方是"多伦多"

if name == "toronto" { self.selectedPlace = annotation }

然后在ViewForantation方法中

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation.coordinate = selectedPlace.coordinate {
        pin.image = UIImage(named: "YOUR SELECTED IMAGE")
    }
}

请参阅此处的演示以创建自定义PIN视图自定义PinannotationButton

这是用图像绘制注释的方法,我属于MKAnoationView

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
    { 
        if annotation is MyAnnotation == false
        {
            return nil
        }
        let senderAnnotation = annotation as! MyAnnotation
        let pinReusableIdentifier = senderAnnotation.pinColor.rawValue
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: pinReusableIdentifier)
        if annotationView == nil
        {
            annotationView = MKAnnotationView(annotation: senderAnnotation,                                                                                                reuseIdentifier: pinReusableIdentifier)
            annotationView!.canShowCallout = false
        }
        if senderAnnotation.pinColor == PinColor.Green
        {
                let pinImage = UIImage(named:"directMarker3.png")
                annotationView!.image = pinImage
        }

      return annotationView
}

在这里添加注释

    let blueLocation = CLLocationCoordinate2D(latitude:30.45454554, longitude: 29.646727)
    let blueAnnotation = MyAnnotation(coordinate: blueLocation, title:"ghghhg",subtitle: "hgnhhghghg",pinColor: .Green ,uid:"hghg",type:"provider")
    self.mymap.addAnnotation(blueAnnotation)        
    self.mymap.showAnnotations(self.mymap.annotations, animated: true)

1.定义mkpointannotation的子类:

class MyPointAnnotation: MKPointAnnotation {
    var imageName: String = ""
}

2.设置图像名称。

    let annotation = MyPointAnnotation()
    annotation.coordinate = coordinate
    annotation.title = "title"
    annotation.subtitle = "subtitle"
    annotation.imageName = "pin" // Set image name here
    self.mapView.addAnnotation(annotation)

3.加载 viewFor委托法中的图像

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }
    let reuseId = "image"
    var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
    if pinView == nil {
        pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView?.canShowCallout = true
        let annotation = annotation as! MyPointAnnotation
        pinView?.image = UIImage(named: annotation.imageName)
        let rightButton: AnyObject! = UIButton(type: UIButtonType.detailDisclosure)
        pinView?.rightCalloutAccessoryView = rightButton as? UIView
    }
    else {
        pinView?.annotation = annotation
    }
    return pinView
}

最新更新