how to add compass to mapview

2019-07-23 07:23发布

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条回答
我只想做你的唯一
2楼-- · 2019-07-23 08:09

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.

查看更多
登录 后发表回答