Android Google Map InfoWindow anchor point after marker rotation
How to reset marker's InfoWindows anchor point after marker has been rotated to be always in top middle? The problem is that the anchor point is rotated along with marker.
static final LatLng PERTH = new LatLng(-31.90, 115.86);
Marker marker = mMap.addMarker(new MarkerOptions()
.position(PERTH)
.anchor(0.5,0.5)
.rotation(90.0)
.infoWindowAnchor(0.5,0));
//Update marker with new data (position and direction angle)
var angle = 130.0;
marker.setPosition(new LatLng(-30.20, 113.27));
marker.setRotation(angle);
marker.setInfoWindowAnchor(x,y); // how to calculate these values?
Solution 1:
var angle = 130.0; // rotation angle
var x = Math.sin(-angle * Math.PI / 180) * 0.5 + 0.5;
var y = -(Math.cos(-angle * Math.PI / 180) * 0.5 - 0.5);
marker.setInfoWindowAnchor((float)x, (float)y);
Explanation:
If we assume that map marker is circular shape (most reasonable for rotation purpose) and as we know that InfoWindow anchor point (B) can be set to any relative coordinate point from 0.0,0.0 (upper left) to 1,1 (lower right) we can find any point on circle line by given rotation degree using SIN and COS formulas.
X distance between A and B = Radius * SIN(degree); Y distance between A and B = Radius * COS(degree);
Adopting them for Android marker coordinates we get:
var x = Math.sin(-angle * Math.PI / 180) * 0.5 + 0.5;
- We find SINE from oposit rotation angle (negative value) converted to radians (degree * PI/180);
- Multiply by circle radius(0.5) to get distance on X axis;
- Shift to RIGHT by radius(+0.5) to be in the middle of shape (on X axis);
var y = -(Math.cos(-angle * Math.PI / 180) * 0.5 - 0.5);
- Find COSINE from oposit rotation angle (negative value) converted to radians (degree * PI/180);
- Multiply by circle radius(0.5) to get distance on Y axis;
- Shift UP by radius(-0.5) to be on the top of shape (on Y axis);
- Make value positive(with - sign) as marker coordinate system has positive values on Y axis downwards;