roy mathew
roy mathew

Reputation: 7800

Issue in setting latitude and longitude in android

I am trying to pass latitude and longitude to another activity and check the distance between this passed co-ordinates and the current co-ordinate.

In the first activity:

 GeoPoint p1 = mapView.getProjection().fromPixels((int) event.getX(),(int event.getY());
 setter(p1.getLatitudeE6()/ 1E6, p1.getLongitudeE6() /1E6);

 public void setter(Double lati,Double longi)
    {
        latitude=lati;
        longitude=longi;
    }

on the button click event i am passing this with the help of a bundle. This works fine.

In the second activity:

public Location selected_location=null;
Double lati,longi;

Bundle b=this.getIntent().getExtras();
        lati=b.getDouble("latitude");
        longi=b.getDouble("longitude");

Till this much it works fine. I even printed the values. The real issue is the the lines given below:

selected_location.setLatitude(lati);
selected_location.setLongitude(longi);

I am trying to set the passed latitude and longitude values to a location variable. But this is causing the activity to terminate.

If possible please suggest a solution. If the question is childish please ignore.

Upvotes: 1

Views: 380

Answers (2)

Boris Strandjev
Boris Strandjev

Reputation: 46953

If you aim to calculate only the distance you do not need to construct Location objects use this method. It is static and works with long and lat values. I can also help debuging the error if you put the stack trace of the exception.

EDIT The requested example:

float myGetDistance(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
  float [] results = new float[1]; // You need only the distance, thus only one element
  Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
  return results[0];
}

Upvotes: 1

Stefan
Stefan

Reputation: 4705

You can complete the distance between two points given by it coordinates like this:

final float[] results= new float[1];
// The computed distance in meters is stored in results[0].
// If results has length 2 or greater, the initial bearing is stored in results[1].
// If results has length 3 or greater, the final bearing is stored in results[2].
Location.distanceBetween(refLat, refLong, latitude, longitude, results);
final float distance = results[0]; // meter!

You may reuse the results array for later computations. If you need bearing information use declare the result array of size 3, if you do not need it use size 1 and save the time for the computation of the not needed information this way.

Upvotes: 0

Related Questions