1

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

2 Answers 2

1

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.

0

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.

3
  • I have changed the direction of the arrow and used Math.atan2 still not working properly.Accuracy improved but still in some cases its not showing the the direction properly
    – Altaf
    Commented Jun 25, 2011 at 16:33
  • How much 'off' is it, and in what cases?
    – Geobits
    Commented Jun 26, 2011 at 7:23
  • What about Bearing ? Location.BearingTo(location2) ??
    – MSaudi
    Commented Oct 18, 2012 at 8:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.