Reputation: 895
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);
}
}
Upvotes: 0
Views: 3186
Reputation: 15669
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()
Upvotes: 0