Turn the marker depending on the direction of travel

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

pic

When a user drives a car, I want to turn it based on its direction of movement. How can i achieve this? I probably should use the previous location and current location coordinates for the calculation, but I have no idea how to do this.

+7
android google-maps direction angle
source share
1 answer

If you use GPS to search for a user, then the Location object that you get in onLocationChanged contains bearing .

If you have only two coordinates (for example, you only have coordinates from the network location provider), you can use Location.bearingTo() to calculate the reference coordinates of the 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 must set the anchor to the point you want to rotate, and this is also the point you want to see at the position set on the marker. (0.5, 0.5) is the center of the image.

+25
source share

All Articles