Пользовательский маркер на Google Map в Swift - PullRequest
0 голосов
/ 01 июня 2018

Я пытаюсь показать свой пользовательский вид на клике на карте Google.Я испортил свой пользовательский вид для него в xib-файле и вызвал этот файл в методе делегата func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { Но когда я запускаю приложение и нажимаю на маркер, он не показывает мой вид.Как я могу показать это?Это мой код для пользовательского файла Xib,

class MapMarkerWindow: UIView {

    @IBOutlet weak var saloonImage: UIImageView!
    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var addressLbl: UILabel!
    @IBOutlet weak var descriptionLbl: UILabel!
    var spotData: NSDictionary?


    class func instanceFromNib() -> UIView {
        return UINib(nibName: "MapMarkerWindowView", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView     
    }
}

Это код в моем VC, где я показываю свою карту,

@IBOutlet weak var customView: UIView!

var mapView : GMSMapView?
var locationManager = CLLocationManager()
private var infoWindow = MapMarkerWindow()
fileprivate var locationMarker : GMSMarker? = GMSMarker()

override func viewDidLoad() {
    super.viewDidLoad()

    self.infoWindow = loadNiB()
    GMSServices.provideAPIKey("AIzaSyBMppjEPlRBHUD4To2KqNLgmhu1QcxHg3g")

    let camera = GMSCameraPosition.camera(withLatitude: 31.516331, longitude: 74.342792, zoom: 6)

    mapView = GMSMapView.map(withFrame: .zero, camera: camera)
    view = mapView

    let states = [
        State(name: "Hafeez Center", long: 74.342792, lat: 31.516331, snippets: "Lahore"),
        State(name: "Kalma Chowk", long: 74.331553, lat: 31.504532, snippets: "Lahore"),
        // the other 51 states here...
    ]

    for state in states {
        let state_marker = GMSMarker()
        state_marker.position = CLLocationCoordinate2D(latitude: state.lat, longitude: state.long)
        state_marker.title = state.name
        state_marker.snippet = "Hey, this is \(state.snippets)"
        state_marker.map = mapView
    }

    self.mapView?.isMyLocationEnabled = true

    //Location Manager code to fetch current location
    self.locationManager.delegate = self
    self.locationManager.startUpdatingLocation()
}

func loadNiB() -> MapMarkerWindow {
    let infoWindow = MapMarkerWindow.instanceFromNib() as! MapMarkerWindow
    return infoWindow
}

//Location Manager delegates
private func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations.last

    let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0)

    self.mapView?.animate(to: camera)

    //Finally stop updating location otherwise it will come again and again in this delegate
    self.locationManager.stopUpdatingLocation()

}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    var markerData : NSDictionary?
    if let data = marker.userData! as? NSDictionary {
        markerData = data
    }
    locationMarker = marker
    infoWindow.removeFromSuperview()
    infoWindow = loadNiB()
    guard let location = locationMarker?.position else {
        print("locationMarker is nil")
        return false
    }
    // Pass the spot data to the info window, and set its delegate to self
    infoWindow.spotData = markerData
    //infoWindow.delegate = self
    // Configure UI properties of info window
    infoWindow.alpha = 0.9
    infoWindow.layer.cornerRadius = 12
    infoWindow.layer.borderWidth = 2
    //infoWindow.infoButton.layer.cornerRadius = infoWindow.infoButton.frame.height / 2
    let saloonImage = markerData!["image"]!
    let name = markerData!["name"]!
    let address = markerData!["address"]!
    let description = markerData!["description"]!

    infoWindow.addressLbl.text = address as? String
    infoWindow.nameLbl.text = name as? String
    infoWindow.descriptionLbl.text = description as? String
    infoWindow.saloonImage.image = saloonImage as? UIImage
    //Offset the info window to be directly above the tapped marker
    infoWindow.center = mapView.projection.point(for: location)
    infoWindow.center.y = infoWindow.center.y - 82
    self.view.addSubview(infoWindow)
    return false
}

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
    if (locationMarker != nil){
        guard let location = locationMarker?.position else {
            print("locationMarker is nil")
            return
        }
        infoWindow.center = mapView.projection.point(for: location)
        infoWindow.center.y = infoWindow.center.y - 82
    }
}

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
    infoWindow.removeFromSuperview()
}

Так выглядит мой пин, когда янажмите на него.enter image description here

Ответы [ 2 ]

0 голосов
/ 28 декабря 2018

Просто установите ваш делегат mapView в viewDidLoad ()

self.mapView.delegate = self
0 голосов
/ 02 июня 2018

Из вашего кода кажется, что есть проблема с загрузкой Nib.

Пожалуйста, проверьте ниже код.

    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        self.tappedmarker = marker
        var point = mapView.projection.point(for: marker.position)
        point.y = point.y - 110
        let camera = mapView.projection.coordinate(for: point)
        let position = GMSCameraUpdate.setTarget(camera)
        mapView.animate(with: position)

        self.customMarker = CustomMarker.instancefromNib() as! CustomMarker
        customMarker.layer.cornerRadius = 10.0
        customMarker.clipsToBounds = true

        self.customMarker.center = mapView.projection.point(for: marker.position)
        self.customMarker.center.y = self.customMarker.center.y - 110
        self.view.addSubview(self.customMarker)
        self.customMarker.bringSubview(toFront: self.view)

        return true
    }

    func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
        if (tappedmarker != nil) {
            guard let location = tappedmarker?.position else {
                print("locationMarker is nil")
                return
            }
            customMarker.center = mapView.projection.point(for: location)
            customMarker.center.y = customMarker.center.y - 100
        }
    }

    func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
        if self.view.subviews .contains(self.customMarker) {
            self.customMarker.removeFromSuperview()
            return
        }
    }

Вот пример instanceNib:

   class CustomMarker: UIView {

    @IBOutlet weak var lblTitle: UILabel!

    class func instancefromNib() -> UIView {
        return UINib.init(nibName: "CustomMarker", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView
    }

}

Это будет выглядеть так: enter image description here

Надеюсь, это поможет!

...