I am working with MapKit for the primary time, making an attempt to make a easy app that exhibits all the closest thrift shops. I do not actually know easy methods to work with annotations and have simply been looking out by the apple documentation and making an attempt to implement their examples. I believed that this code would work, but it surely nonetheless is not.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var coordinates: [String] = [""] //latitude, longitude
var firstTime = true
override func viewDidLoad() {
tremendous.viewDidLoad()
print("View loaded...")
theMap.delegate = self //this doesnt crash although so ig the iboutlet creates an occasion
locationManager = CLLocationManager() //gotta create occasion of sophistication first. else it crashes
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.requestLocation()
}
@IBOutlet weak var theMap: MKMapView!
var locationManager: CLLocationManager!
func locationManager(_ supervisor: CLLocationManager, didUpdateLocations places: [CLLocation]) {
if firstTime {
firstTime = false
theMap.isHidden = false
let myLocation: CLLocation = places[0]
let coordinates = CLLocationCoordinate2D(latitude: myLocation.coordinate.latitude, longitude: myLocation.coordinate.longitude)
let area = MKCoordinateRegion(middle: coordinates, latitudinalMeters: 5000, longitudinalMeters: 5000)
theMap.setRegion(area, animated: true)
theMap.showsUserLocation = true
print("Setting the middle of the map...")
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = "thrift retailer"
searchRequest.area = theMap.area
let search = MKLocalSearch(request: searchRequest)
search.begin { (response, error) in
guard let response = response else {
return
}
for merchandise in response.mapItems {
let annotation = MKPlacemark(coordinate: merchandise.placemark.coordinate)
self.theMap.addAnnotation(annotation)
}
}
}
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation{
return nil;
}else{
let pinIdent = "Pin";
var pinView: MKPinAnnotationView;
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: pinIdent) as? MKPinAnnotationView {
dequeuedView.annotation = annotation;
pinView = dequeuedView;
}else{
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: pinIdent);
}
return pinView;
}
}
func locationManager(_ supervisor: CLLocationManager,
didFailWithError error: Error) { print("Error fetching location") }
}
I’ve solely tried a number of the instance code within the Apple documentation and have not messed round with it a lot as a result of I am nonetheless very new to Swift (ab a month of expertise) and am unfamiliar with these frameworks.