1

I want to calculate the distance Between two location(i.e current location of user and destination location). I have latitude and longitude of destination places in my database and current location(i do find by Location Manager class). I need to display that calculated distance in a listview. if i calculate it by any Mathematical formulae or DistanceTo() and DistanceBetween() method of Location class then I don't get accurate distance as over map. and if i calculate the distance by Distance Matrix API of Google then its taking too much time to calculate the distance and in loading the list.(as there are lots of destination places with one current location of user) Please anyone suggest me the best way to calculate it.. i am stuck in this problem from last few days..Help me Thanks in advance...

kirti Hudda
  • 304
  • 3
  • 17
  • Check this link http://stackoverflow.com/questions/10683554/distance-calculation-from-my-location-to-destination-location-in-android – IntelliJ Amiya Apr 08 '14 at 10:11
  • 1
    Hello @Amiya..First of all Thanks for your support.I have already tried it by five ways- 1.DistanceTo() 2.Distance Between() 3.Mathematical Formulae 4.Google Map API V3 5.Google Map API V2.Now problem with 1 to 4 is not getting correct output and with Google API V2 is its taking lots of time,because i am calculating distance of near about 100 places at a time from user current position and then loading this distance in a List-view. Due to that time taken processing my List-view is not scrolling properly – kirti Hudda Apr 08 '14 at 12:14
  • DistanceTo() and DistanceBetween() always return displacement between the two Coordinates, that's why you are not getting accurate result.So what you can do is place your other mathematical formula's in AsyncTask or use thread to calculate the distance,just make sure you are not blocking main thread.Good luck!!!! – Pankaj Apr 09 '14 at 06:41
  • @ANdroidGreek Thanks. Could you Please suggest me mathematical formulas helpful for me??I have tried below calculateByDisplacement()..but its not of use.. – kirti Hudda Apr 09 '14 at 07:33

3 Answers3

2

Finally after lots of googling I have done my task.I tried it by Asynchronous Task.. Here is my code..

public View getView(int position, View convertView, ViewGroup Parent) 
  {
 final ViewHolder holder=new ViewHolder();
 View view=convertView;
 if (view==null) {
     convertView= inflater.inflate(R.layout.layout_row, null);
 }



holder.textdistance=(TextView) convertView.findViewById(R.id.textView_Distance);

   holder.position = position;


  if(data.size()<=0)
   {

   Toast.makeText(activity, "No data", Toast.LENGTH_LONG).show();
  }
  else
  {
   **new ThumbnailTask(position, holder)
   .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);**
   }
 return convertView;



  }
   //Thumbnail Class
 private static class ThumbnailTask extends AsyncTask {
    private int mPosition;
    private ViewHolder mHolder;

    public ThumbnailTask(int position, ViewHolder holder) {
        mPosition = position;
        mHolder = holder;
    }



    /* (non-Javadoc)
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Object doInBackground(Object... params) {
        // TODO Auto-generated method stub
        String Distance="3";
         String uri="https://maps.googleapis.com/maps/api/distancematrix/json?  origins=(Your source Addres like XYZ,South Delhi-110064),&mode=deriving&sensor=false&key=(Your API Key)";


            String result= GET(uri);
            Log.d("result","res="+result);

             try {

                    //jArray = new JSONObject(result);
                     JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
                     JSONArray array = object.getJSONArray("rows");
                    // Log.d("JSON","array: "+array.toString());

                 //Routes is a combination of objects and arrays
                 JSONObject rows = array.getJSONObject(0);
                     //Log.d("JSON","routes: "+routes.toString());
                 JSONArray elements = rows.getJSONArray("elements");
                // Log.d("JSON","legs: "+legs.toString());

                JSONObject steps = elements.getJSONObject(0);
                     //Log.d("JSON","steps: "+steps.toString());

                JSONObject distance = steps.getJSONObject("distance");
                 Log.d("JSON","distance: "+distance.toString());

                   Distance = distance.getString("text");
                    Log.d("final value","tot dis="+Distance);
                    JSONObject duration=steps.getJSONObject("duration");
                 // MyDuration=duration.getString("text");


                 }
                 catch(JSONException e)
                         {
                     Log.d("JSONEXCeption","my exce"+e.getMessage());
                         }
             return Distance;
    }



    @Override
    protected void onPostExecute(Object result) {
        // TODO Auto-generated method stub
    mHolder.textdistance.setText(result.toString());
    }


}

 //method to execute Url

 private static  String GET(String url)
   {
    InputStream inputStream = null;
   String result = "";
    try {

     // create HttpClient
     HttpClient httpclient = new DefaultHttpClient();

     // make GET request to the given URL
     HttpResponse httpResponse = httpclient.execute(new HttpGet(url));


     // receive response as inputStream
     inputStream = httpResponse.getEntity().getContent();



     // convert inputstream to string
     if(inputStream != null)
         result = convertInputStreamToString(inputStream);

//     Log.i("Result",result);

     else
         result = "Did not work!";

 } catch (Exception e) {
     Log.d("InputStream", "hello"+e);
 }

 return result;




   }


 private static  String convertInputStreamToString(InputStream inputStream) throws   IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }


 }  

Reference Links are-

http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/ https://developers.google.com/maps/documentation/distancematrix/

I am not good in explaining but i am trying my best.Hope it would help to others people like me as i got stuck in this task.

kirti Hudda
  • 304
  • 3
  • 17
1

Try this .I add this in my old application. It works for me .By the way Initialize R=Radius . Read this article carefully

 public double CalculationByDistance(GeoPoint StartP, GeoPoint EndP) {
      double lat1 = StartP.getLatitudeE6()/1E6;
      double lat2 = EndP.getLatitudeE6()/1E6;
      double lon1 = StartP.getLongitudeE6()/1E6;
      double lon2 = EndP.getLongitudeE6()/1E6;
      double dLat = Math.toRadians(lat2-lat1);
      double dLon = Math.toRadians(lon2-lon1);
      double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
         Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
         Math.sin(dLon/2) * Math.sin(dLon/2);
      double c = 2 * Math.asin(Math.sqrt(a));
      return Radius * c;
   }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
  • 2
    Well Thanks ,I have tried it already as i mentioned above mathematical formulae(In that I tried the same). Its giving different output with the output over map .. – kirti Hudda Apr 09 '14 at 06:04
  • 1
    @kirtiHudda Please follow this link http://stackoverflow.com/questions/22351984/how-to-find-the-distance-between-two-points-along-a-specific-route?rq=1 – IntelliJ Amiya Apr 10 '14 at 05:25
1

If there are many locations use a loop. Only a few lines of code to get this done:

Location l1=new Location("One");
l1.setLatitude(location.getLatitude());
l1.setLongitude(location.getLongitude());

Location l2=new Location("Two");
l2.setLatitude(Double.parseDouble(frnd_lat));
l2.setLongitude(Double.parseDouble(frnd_longi));

float distance_bw_one_and_two=l1.distanceTo(l2);
TharakaNirmana
  • 10,237
  • 8
  • 50
  • 69