0
votes

I am very confused why this is displaying the default image instead of a round blue circle over New York. Any insight about this as well as when the default image is used will be greatly appreciated.

import UIKit
import Mapbox

class ViewController: UIViewController, MGLMapViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupMapview()
    }

    func setupMapview(){
        let mapView = MGLMapView(frame: view.bounds)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.setCenter(CLLocationCoordinate2D(latitude: 40.74699, longitude: -73.98742), zoomLevel: 9, animated: false)
        view.addSubview(mapView)

        let annotation = MGLPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: 40.77014, longitude: -73.97480)
        mapView.addAnnotation(annotation)

        mapView.delegate = self
    }


    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        print("CORDINATE")
        print(annotation.coordinate)
        if annotation is MGLPointAnnotation {
            print("SET\n\n\n")
            let av = RoundedAnnotationView(annotation: annotation, reuseIdentifier: "ResuseIdentifier")
            av.configure()
            return av
        }
        return nil
    }
}

class RoundedAnnotationView: MGLAnnotationView{
    func configure(){
        backgroundColor = .blue
        layer.cornerRadius = 24
        clipsToBounds = true
    }
}

Output: iPhone_Screen print_statements

2
Are you sure you don't have a typo? reuseIdentifier: "ResuseIdentifier" looks like it should be reuseIdentifier: "ReuseIdentifier". - pawello2222

2 Answers

0
votes

The standard default annotation is being shown in NY because that is exactly what you are adding to the map in setupMapview. If you want the map to display the user's location, you have to tell it to do so:

mapView.addAnnotation(annotation)

mapView.showsUserLocation = true // This needs to be set explicitly.

mapView.delegate = self

As usual, when you want to have access to the user's location you have to ask permission by inserting the correct flag in the info.plist:

Privacy - Location When In Use Usage Description

along with some kind of explanatory string:

"We'd like to track you with our satellite."

If you are running your app on the simulator you can create a custom location:

Simulator -> Features -> Location -> Custom Location...

0
votes

Annotations should be added after the map has completely loaded. I have a more detailed step by step solution: https://github.com/mapbox/mapbox-gl-native/issues/16492