Robin Robin - 8 months ago 32
Swift Question

Change coordinate of map (MapKit)

I want change the location of my map with personnal coordonate.
(when I say "personnal", is not the "user location" but just random coordonate).

This is my MapView Controller :

class MapSubViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!

let regionRadius: CLLocationDistance = 1000

override func viewDidLoad() {
self.mapLocationUpdate(70.0, longitude: 70.0, title: "")

func mapLocationUpdate(latitude: Double, longitude: Double, title: String) {
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
self.centerMapOnLocation(location, title: title)

func centerMapOnLocation(location: CLLocationCoordinate2D, title: String) {
let coordinateRegion = MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(coordinateRegion, animated: false)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = title


I tell my function "mapLocationUpdate" when i want change the location of my map :

Here for example :

func addMapView(xPosition: Double, yPosition: Double, title: String) {
self.mapSubViewController = (self.storyboard!.instantiateViewControllerWithIdentifier("MapSubViewController") as? MapSubViewController)!
self.mapSubViewController.mapLocationUpdate(xPosition, longitude: yPosition, title: clubName)

My app crash when the line "self.mapSubViewController.mapLocationUpdate(...)" is executed. When it's the "viewDidLoad" of the controller who tell the function "mapLocationUpdate", the app not crash.

I think it's because the map location cannot be change in the code after the map charged.

How i can do ?

Sorry for my english, I do my best :-) !

Thx !


In order to set a custom location on a map you should to something similar to this:

let pLat = 43.6109200
let pLong = 3.8772300
let center = CLLocationCoordinate2D(latitude: pLat, longitude: pLong)

let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

self.mapView.setRegion(region, animated: true)