Rotate marker to the device heading at precise location when map is rotating.

1.5k views Asked by At

Using new version of mapsforge 0.5.1, map rotates fine with onSensorChanged event. I have added a custom GPS location marker at GPS point on onLocationChanged event. When the map rotates, the marker is also rotated to point towards the device heading like in google maps using the following code in the marker's draw method.

android.graphics.Canvas androidCanvas = AndroidGraphicFactory.getCanvas(canvas);
androidCanvas.save();
Float px = (float) canvas.getWidth()/2;
Float py = (float) canvas.getHeight()/2;
androidCanvas.rotate(degree, px, py);
canvas.drawBitmap(bitmap, left, top);
androidCanvas.restore();

enter image description here

However when the map is dragged, the marker's position disorients from the previous point of the GPS location.

enter image description here

How do I calculate the px and py value to keep the marker at the precise point of GPS location on map even when the map is rotating and also the marker pointing to the device heading.

1

There are 1 answers

0
jav974 On

I know it is a bit old, but for future researches i found a solution :

  • First extend mapsforge Marker and override its draw() method
  • Copy paste the content of the draw method from Marker
  • then add the following in the last condition :

Replace this :

if(canvasRectangle.intersects(bitmapRectangle)) {
    canvas.drawBitmap(bitmap, left, top);
}

With this :

if(canvasRectangle.intersects(bitmapRectangle)) {
    // Rotate the marker based on bearing for example (or whatever angle you want)
    android.graphics.Canvas androidCanvas = AndroidGraphicFactory.getCanvas(canvas);
    androidCanvas.save();

    float px = (right + left) / 2f;
    float py = (bottom + top) / 2f;

    androidCanvas.rotate(bearing, px, py);
    canvas.drawBitmap(bitmap, left, top);
    androidCanvas.restore();
}

In my case "bearing" is a member variable of my class extenting Marker, that i set from 2 different locations earlier in code (gps location). you can replace it with any angle that suits your needs.