Search code examples
javaandroidmapsopenstreetmaposmdroid

Rotate a Marker in OSMDroid for Android?


Ok, this one has been bugging me for hours, I have the following relatively simple code that places a marker on a osmdroid map

final ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
OverlayItem marker = new OverlayItem("markerTitle", "markerDescription", new GeoPoint(52.033954,1.210179));
marker.setMarkerHotspot(OverlayItem.HotspotPlace.TOP_CENTER);
items.add(marker);

Drawable newMarker = this.getResources().getDrawable(R.drawable.maincar);
DefaultResourceProxyImpl resProxyImp = new DefaultResourceProxyImpl(getApplicationContext());
ItemizedIconOverlay markersOverlay = new ItemizedIconOverlay<OverlayItem>(items, newMarker, null, resProxyImp);
mapView.getOverlays().add(markersOverlay);

However the marker is always facing the top of the screen (0deg reotation). How can I go about easily rotating each marker to a specified degree (360deg being a full circle)?


Solution

  • Try use RotateMyBitmap method like this:

    Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher);
    
    Bitmap target = RotateMyBitmap(source, 120.0f);
    
    final ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
    OverlayItem marker = new OverlayItem("markerTitle", "markerDescription", new GeoPoint(52.033954,1.210179));
    marker.setMarkerHotspot(OverlayItem.HotspotPlace.TOP_CENTER);
    items.add(marker);
    
    Drawable newMarker = new BitmapDrawable(getResources(), target);
    
    //Drawable newMarker = this.getResources().getDrawable(R.drawable.maincar);
    DefaultResourceProxyImpl resProxyImp = new DefaultResourceProxyImpl(getApplicationContext());
    ItemizedIconOverlay markersOverlay = new ItemizedIconOverlay<OverlayItem>(items, newMarker, null, resProxyImp);
    mapView.getOverlays().add(markersOverlay);
    

    Where RotateMyBitmap is:

    public static Bitmap RotateMyBitmap(Bitmap source, float angle)
    {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    }
    

    Result is:

    enter image description here

    This works fine but I recommend you use MyLocationOverlay class