How can I snap the direction of the compass to the direction of the map?
I add a Compass to my MapView and enable map rotation like this:
MapView mapView = findViewById(R.id.mapView);
// Enable & add compass
CompassOverlay compassOverlay = new CompassOverlay(this, mapView);
compassOverlay.enableCompass();
mapView.getOverlays().add(compassOverlay);
// Enable map rotation with gestures
mapView.getOverlays().add(new RotationGestureOverlay(mapView));
Now when the map is not rotated, so up is north, right is east etc, the compass works correctly. But when I rotate the map with gesture, the compass does not move accordingly. So when the device is faced north and the map is at its default rotation, the compass shows north according to the map, which is correct. But when I rotate the map by 90° clockwise, the compass still points up instead of turning 90° clockwise.
I tried using compassOverlay.setPointerMode(true); but that only changed the appearance of the compass.
While digging a bit and considering Peter's answer I found a simple solution (Kotlin):
CompassOverlay instance and override the draw() methodval mapNorthCompassOverlay = object: CompassOverlay(context, mapView) {
override fun draw(c: Canvas?, pProjection: Projection?) {
drawCompass(c, -mapView.mapOrientation, pProjection?.screenRect)
}
}
mapView.overlays.add(mapNorthCompassOverlay)
And that's it.
Explanation: drawCompass() is a protected method, but we can override the public draw() that uses the former method to fetch the phone magnetometer data to get the bearing direction. Since drawCompass() inverts the bearing data to print on your map and that is not our expected behavior, in this case, we pass -mapView.mapOrientation as a parameter, as it contains the information of the north of our map. Also, this CompassOverlay does not require you to use enableCompass(), which is the method that starts listening for sensor changes in direction, so you won't need to create a fake OrientationProvider to avoid your phone wasting resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With