13

I have a marker in my Google Maps map that looks like this:

pic

When the user is driving, I want to rotate it based on his driving direction. How can I achieve this? I should probably use previous location and current location coords for calculation, but I have no idea how.

Gintas_
  • 4,940
  • 12
  • 44
  • 87
  • You obviously know how to find the position. Before the first loop set the previous pos same as current. Then your loop continually calculates the distance between the previous and the current positions and when it is large enough to matter, the direction with something like `atan2(dy,dx)` at which point you set the marker orientation, then remember `previous == current` and do another loop. – Weather Vane Nov 23 '14 at 17:54
  • Why don't you use `bearing` of the `Location` object? You can set it to the `CameraPosition`. – romtsn Nov 23 '14 at 18:10
  • how do I do it in the leaflet api? – ShAkKiR Sep 18 '19 at 22:31

1 Answers1

40

If you use GPS for locating the user then the Location object you get in onLocationChanged contains the bearing.

If you only have the two coordinates (e.g. you only have coordinates from network location provider), you can use Location.bearingTo() to calculate the bearing of two coordinates:

Location prevLoc = ... ;
Location newLoc = ... ;
float bearing = prevLoc.bearingTo(newLoc) ;

If you have a bearing, you can set the rotation of the marker using MarkerOptions.rotation():

mMap.addMarker(new MarkerOptions()
                    .position(markerLatLng)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker))
                    .anchor(0.5f, 0.5f)
                    .rotation(bearing)
                    .flat(true));

You have to set the anchor to the point you want to rotate around, and it's also the point you want to be at the position you set to the marker. (0.5, 0.5) is the center of the image.

hunyadym
  • 2,213
  • 25
  • 39