3

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?
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

9

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.

Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • This is not showing the compass before the first rotate gesture. It is just "creating" a new one. –  Feb 09 '18 at 20:37
  • The positioning will not let the compass appear before the rotate gesture. –  Feb 09 '18 at 21:37
  • I took this code directly from a test app. The compass appears as soon as the map appears. – Paulw11 Feb 09 '18 at 21:58
  • Would you be so kind to share your app? @Paulw11 Maybe GitHub? I can not find the issue in my code. Thanks in advance. :-) –  Feb 09 '18 at 22:36
  • Thanks so much. I will have a look on your project later, but anyways THANKS! –  Feb 09 '18 at 22:58
  • @thexande Did you try it on a real device? It works for me. Maps can be a bit broken in the simulator. If you rotate the map in the simulator then the compass appears but this is not required on a real phone. – Paulw11 Apr 25 '18 at 05:16