Search code examples
iosswiftmkmapviewcoordinates

How to offset MKMapView to put coordinates under specified point


I have two view controllers. One allows the user to enter their own sightings of things:

enter image description here

The other is a UITableViewController that allows them to see their submitted sightings:

enter image description here

What I want is for the user to be able to click on their sighting in the 2nd VC and for it to populate the 1st VC with the relevant details. I have that working for the textFields using :

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    let pvc = self.navigationController?.previousViewController() as! SubmitSightingVC
    let sighting = sightingsArray[indexPath.row]
    pvc.titleTextField.text = sighting["title"] as! String?
    pvc.locationTextField.text = sighting["location"] as! String?
    pvc.dateTextField.text = sighting["date"] as! String?
    pvc.descriptionTextView.text = sighting["sightingDesc"] as! String?
    
    let pinArray = ["1", "2", "3", "4", "5"]
    let pinTextArray = ["1text", "2text", "3text", "4text", "5text"]
    var pinImageArray = [#imageLiteral(resourceName: "1"), #imageLiteral(resourceName: "2"), #imageLiteral(resourceName: "3"), #imageLiteral(resourceName: "4"), #imageLiteral(resourceName: "5")]
    let pinIconString = sighting["pinIcon"] as! String
    let index = pinArray.index(of: pinIconString)
    
    pvc.pinImageView.image = pinImageArray[index!]
    pvc.pinTextField.text = pinTextArray[index!]
    

    // Bit I'm struggling with:
    var coordinates = CLLocationCoordinate2D(latitude: sighting["latitude"] as! Double, longitude: sighting["longitude"] as! Double)
    pvc.mapView.centerCoordinate = coordinates
    
    self.navigationController!.popViewController(animated: true)
    
}

The problem is that because the centre of the map is behind the blurred view it is offset. The pin on the map isn't an actual pin but a UIImage (pinImageView). How can I move the map so that the coordinates are under this pinImage instead of in the centre of the mapView?


Solution

  • As mentioned above you can use the MKMapCamera to position the view of the map or you can also use setVisibleMapRect and add some padding to position the map like this:

    self.mapView.setVisibleMapRect(self.mapView.visibleMapRect, edgePadding: UIEdgeInsetsMake(200.0, 0.0, 0.0, 0.0), animated: true)
    

    This will offset the center by 200 screen pixels on the top.