Calculate angle between two Latitude/Longitude points

后端 未结 17 1408
故里飘歌
故里飘歌 2020-12-07 17:51

Is there a way to calculate angle between two Latitude/Longitude points?

What I am trying to achieve is to know where the user is heading. For example, user is head

17条回答
  •  盖世英雄少女心
    2020-12-07 18:21

    If your are using google maps(Android), there is an easy way - Use SphericalUtil

    double angle = SphericalUtil.computeHeading(fromLatLng, toLatLng);
    

    Consider we have 2 points and its lat and lng Then create its Latlng object

    LatLng latlng = new LatLng(latValue, lngValue);
    

    After getting Latlng of 2 points, use sperical util to get angle

    //import com.google.maps.android.SphericalUtil;
    double sphericalValue = SphericalUtil.computeHeading(latLng1, latLng2);
    

    SpericalValue is the angle. Consider you have a car icon and turn it accordingly to the direction its going. Here its from latLng1 to latLng2 then

    Bitmap vehiclePin = rotateIconBitmap(sphericalValue);
    mMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).position(latLng2))
                   .setIcon(BitmapDescriptorFactory.fromBitmap(vehiclePin));
    

    use the method below to rotate

        Bitmap rotateIconBitmap(double angle) {
           Bitmap source = BitmapFactory.decodeResource(getResources(), 
                                              R.drawable.ic_vehicle_say_car);
           Matrix matrix = new Matrix();
           matrix.postRotate((float) angle);
           return Bitmap.createBitmap(source, 0, 0, 
                        source.getWidth(), source.getHeight(), matrix, true);
        }
    

    Easy way to achieve uber like rotated icons

    Note:- You may have to add an offset of say 90 degree if the marker icon is not pointed to zero degree

    The android sphericalutil is open source, refer it if you are using java, you can make use of it.

    https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/SphericalUtil.java

提交回复
热议问题