Search code examples
iosswiftmapkitcompass

How to show MapKit compass?


Currently the compass only get's shown if a User applies a rotate-gesture. Otherwise the compass is hidden.

img1


But it would be nice if my two wishes below were fulfilled!

  • Is it possible to display the compass always?
  • How to show / hide the compass-view using Swift?

Solution

  • You can do this quite easily in iOS 11 by using the new MKCompassButton class.

    You need to create an instance of MKCompassButton and add it to your map view. You can then set its compassVisibility property to one of:

    • .visible - always visible
    • .never - never visible
    • .adaptive - the compasss is only visible if the map is rotated away from a North/up orientation.

    If you keep a reference to the compass in a property you can change its visibility as you need:

    mapview.showsCompass = false  // Hide built-in compass
    
    compassButton = MKCompassButton(mapView: mapview)   // Make a new compass
    compassButton.compassVisibility = .visible          // Make it visible
    
    mapview.addSubview(compassButton) // Add it to the view
    
    // Position it as required
    
    compassButton.translatesAutoresizingMaskIntoConstraints = false
    compassButton.trailingAnchor.constraint(equalTo: mapview.trailingAnchor, constant: -12).isActive = true
    compassButton.topAnchor.constraint(equalTo: mapview.topAnchor, constant: 12).isActive = true
    

    Unfortunately, for prior versions of iOS there is no simple solution. I have seen suggestions that involve looking through the map view's subviews to try and find the compass view but there seems to be mixed results.