Rotate marker based on driving direction
Asked Answered
W

1

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.

Wilmington answered 23/11, 2014 at 17:40 Comment(3)
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.Ithunn
Why don't you use bearing of the Location object? You can set it to the CameraPosition.Ingra
how do I do it in the leaflet api?Lahey
C
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.

Chemnitz answered 23/11, 2014 at 21:51 Comment(3)
Based on this answer how does it know the front and the side of the car?Introductory
It doesn't know, it assumes that the car moves forward (it uses two sequential positions, the direction of the movement points to the latter one).Chemnitz
Any idea how to do this on Angular Google Maps?Scourings

© 2022 - 2024 — McMap. All rights reserved.