Rotate marker as per user direction on Google Maps V2 Android

Viewed 30082

I want to rotate marker as per bearing or sensor value received from Accelerometer to show the user where actually he is moving. I have set marker icon and flat value to true but its not working as required.

mCurrentLocationMarker.position(new LatLng(
                            LocationUtils.sLatitude, LocationUtils.sLongitude));
                    mCurrentLocationMarker.icon(icon);
                    mCurrentLocationMarker.flat(true);
                    mCurrentLocationMarker.rotation(LocationUtils.sBearing);

                    if (currentMarker != null) {
                        currentMarker.setPosition(new LatLng(
                                LocationUtils.sLatitude,
                                LocationUtils.sLongitude));
                    } else {
                        currentMarker = mGoogleMap
                                .addMarker(mCurrentLocationMarker);
                    }
                    animateCameraTo(true);

I have used this marker as marker.

I don't know why its not rotating as per user's direction. If anyone has any idea please kindly help me where i am making mistake.

LocationUtils.sBearing is the value of Bearing which i received from onLocationChanged or accelerometer.

Basically I want to make my marker same as google maps marker which shows user in which direction they are moving or turning.

3 Answers

In Kotlin by using Google SphericalUtil class we can get bearing by passing source and destination LatLngs like:

fun calculateBearing(lat1: Double, lng1: Double, lat2: Double, lng2: Double): Float {
        val sourceLatLng = LatLng(lat1, lng1)
        val destinationLatLng = LatLng(lat2, lng2)
        return SphericalUtil.computeHeading(sourceLatLng, destinationLatLng).toFloat()
    }

Then set this result 'bearing` to the marker like

Val bearing  = calculateBearing(lat1, lng1, lat2, lng2)
marker.rotation(bearing)

Reference: https://developers.google.com/maps/documentation/android-sdk/utility/#spherical

Related