0
votes

I am using Mapbox to create my app. When I click a button I would like it to mark my current location and add a marker to it as it currently does. I then would like the abiilty to tap on this marker and have it display the current location information such as the adress of the marked point.

Right now all I have is...

https://imgur.com/a/RSx0G

I would like to note that I am using Xcode 9.1 and Swift 4. Thank you for all your feedback in advance.

Currently the swift file looks like...

import Foundation
import UIKit
import CoreLocation
import Mapbox
import MapKit
import MapboxGeocoder

class SecondViewController: UIViewController, CLLocationManagerDelegate, MGLMapViewDelegate, UITextFieldDelegate {

let geocoder = Geocoder.shared

let dismissesAutomatically: Bool = false
let isAnchoredToAnnotation: Bool = true

weak var delegate: MGLCalloutViewDelegate?

let tipHeight: CGFloat = 10.0
let tipWidth: CGFloat = 20.0

@IBOutlet var mapView: MGLMapView!
let manager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

@IBAction func markStuff(_ sender: Any) {
}
@IBAction func refLocation(_ sender: Any) {
manager.startUpdatingLocation()

}
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}


func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
return nil
}

    func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation)
{

 print("tap on callout")

}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]

let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

mapView.setCenter(center, zoomLevel: 10, animated: true)

let annotation = MGLPointAnnotation()

annotation.coordinate = location.coordinate

mapView.selectAnnotation(annotation, animated: true)

annotation.title = "Testing"
annotation.subtitle = "\(annotation.coordinate.latitude), \(annotation.coordinate.longitude)"

self.mapView.addAnnotation(annotation)

manager.stopUpdatingLocation()
1

1 Answers

1
votes

You can create a subclass of MGLUserLocationAnnotationView, then use that as your view for the MGLUserLocation annotation.

For example, if your custom subclass was called YourLocationAnnotationView(), you could do something like:

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {This custom view is created below.
     if annotation is MGLUserLocation && mapView.userLocation != nil {
        return YourLocationAnnotationView()
    }
    return nil
  }
}

For a complete implementation, see this example from the official documentation.