Altaf
Altaf

Reputation: 5170

Direction between two GeoPoints in Google map in android

I am developing an android application in I have two GeoPoints in Google map.One GeoPoint is fix and other GeoPoint is my current location. On my current location I am placing an arrow point in direction of fix GeoPoint,as my current location changes so the arrow will change its direction.It works fine but in most cases it showing wrong direction.

Here is my code.

            Paint paint = new Paint();
        GeoPoint gp1;
        GeoPoint gp2;
        Point point1,point2;
        Projection projection = mapView.getProjection();
        projection.toPixels(gp1, point1);
        projection.toPixels(gp2, point2);
        Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.arrow);
        double dlon = gp2.getLongitudeE6() - gp1.getLongitudeE6();
        double dlat = gp2.getLatitudeE6() - gp1.getLatitudeE6();
        double a = (Math.sin(dlat / 2) * Math.sin(dlat / 2)) + Math.cos(gp1.getLatitudeE6()) * Math.cos(gp2.getLatitudeE6()) * (Math.sin(dlon / 2) * Math.sin(dlon / 2));
        double angle = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        Matrix matrix = new Matrix();
        matrix.postTranslate(-25, -25);
        matrix.postRotate(convertToRadians(angle));
        matrix.postTranslate(point1.x, point1.y);       
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        canvas.drawBitmap(bmp, matrix, paint);

Waiting for your help and thanks in advance.

Altaf

Upvotes: 1

Views: 3154

Answers (2)

Nilay
Nilay

Reputation: 11

Use projection points for angle calculation instead of geolocation points, because your arrow will be showing direction of projected points.

Replace

double dlon = gp2.getLongitudeE6() - gp1.getLongitudeE6();
double dlat = gp2.getLatitudeE6() - gp1.getLatitudeE6();

with

double dlon = point2.x - point1.x;
double dlat = point2.y - point1.y;

For angle calculation, formula suggested by 'Geobits' is simpler & better.

double angle = Math.atan2(dlat, dlon);

I thoroughly tested this code, and it works for all cases in my App.

Upvotes: 1

Geobits
Geobits

Reputation: 22342

Where did you get that formula? It seems incredibly complex for a simple angle calculation. Normally I just use atan2 with y, x :

double angle = Math.atan2(dlat, dlon); // in radians

This is assuming your arrow is pointing along the horizontal axis(due east) by default. You might have to tweak it by whatever direction your arrow drawable is pointing. For example, if it's pointing a constant 90 degrees off, just rotate it an additional 0.5*PI rads to align it.

Upvotes: 0

Related Questions