How do I get the compass to be shown on the screen when my mapview is created. What is wrong with this code? any suggestions?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
myLoc = new MyLocationOverlay(this, mapView);
myLoc.enableCompass();
mapView.getOverlays().add(myLoc);
mapView.postInvalidate();
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Well, I wouldn't call
enableCompass()
ononCreate()
(which is where I assume this code comes from, given thesetContentView()
call). Enable the compass inonResume()
and disable it inonPause()
, so you don't keep the sensors alive when your activity is not on-screen. And you should not needpostInvalidate()
.Otherwise, this seems fine. Bear in mind that it will only work on actual hardware.
Here is a sample project that enables the compass on
MyLocationOverlay
that definitely works, though you will need to substitute in your ownandroid:apiKey
value.