问题
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);
回答1:
Well, I wouldn't call enableCompass()
on onCreate()
(which is where I assume this code comes from, given the setContentView()
call). Enable the compass in onResume()
and disable it in onPause()
, so you don't keep the sensors alive when your activity is not on-screen. And you should not need postInvalidate()
.
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 own android:apiKey
value.
来源:https://stackoverflow.com/questions/5750897/how-to-add-compass-to-mapview