0

I'm trying to make MyLocationOverlay compass to point to a particular location. I want to show a direction from current user's location to a given location. So far I've managed to calculate a direction and pass it to MyLocationOverlay. But the compass arrow starts pointing to different locations chaotically. Sometimes it points to the right direction but usually it shows complete nonsense.

Is there a way to make the compass work as it should?

This is how I calculate the direction in my activity

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(location != null && carOverlay.size() > 0 
                && !map.getUserOverlay().isPointingToNorth()) {

            float azimuth = event.values[0];
            azimuth = azimuth * 180 / (float) Math.PI;
            GeomagneticField geoField = new GeomagneticField(
                    Double.valueOf(location.getLatitude()).floatValue(),
                    Double.valueOf(location.getLongitude()).floatValue(),
                    Double.valueOf(location.getAltitude()).floatValue(),
                    System.currentTimeMillis());
            azimuth += geoField.getDeclination();

            GeoPoint point = carOverlay.getItem(0).getPoint();
            Location target = new Location(provider);
            float lat = (float) (point.getLatitudeE6() / 1E6f);
            float lon = (float) (point.getLongitudeE6() / 1E6f);
            target.setLatitude(lat);
            target.setLongitude(lon);

            float bearing = location.bearingTo(target);
            float direction = azimuth - bearing;

            map.getUserOverlay().putCompassDirection(direction);
        }
    }

This is the overriden method in my custom overlay

@Override
    protected void drawCompass(Canvas canvas, float bearing) {
        if(pointToNorth) {
            super.drawCompass(canvas, bearing);
        }
        else {
            super.drawCompass(canvas, compassDirection);
        }

    }
droid8421
  • 895
  • 1
  • 13
  • 26
  • "Sometimes it points to the right direction but usually it shows complete nonsense." Even a broken clock is right twice a day :) – Rafael T Jun 07 '12 at 08:14

1 Answers1

0

Why do you calculate your "bearing/azimuth" yourself? MyLocationOverlay hold the Method getOrientation() to give you the azimuth. I would definetly leave onSensorChanged untouched, and let the MyLocationOverlay calculate this for you. Normally to draw your Compass correct you just have to call enableCompass()

Rafael T
  • 15,401
  • 15
  • 83
  • 144
  • I calculate the direction myself because I want the compass to point to a specific overlay item on the map. Basically, the user can toggle a button to either point the compass to north or to a location on the map. – droid8421 Jun 07 '12 at 08:40