3

Work Summary..

I'm working on project where we calculate the driving distance from user current location and nearby user location.

It can be a duplicate question for single point distance calculation but i want distance calculation for multiple location in custom listview.

Other Nearby user locations comes from web api with their name and detail info.

To get the driving distance between two points I'm using the google direction api.

It will give me the result but it slows down the app and if there is more data then it will hang the device..

Requirement :

I need to find out the driving distance between two location in custom List View accurate and smoothly..

What I've Done :

I found this Link Async Loading but it also not work properly. App crashed when scroll the listview.

Here is the code of Async Loading..

   @Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    viewHolder holder;

    if (convertView == null) {
        holder = new viewHolder();
    } else {
        holder = (viewHolder) convertView.getTag();
    }

    new getDistanceAsyncTask(position, holder, userLatt, userLong, sLatt1, sLong1).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);

    return convertView;
}


 private static class getDistanceAsyncTask extends AsyncTask {
    private int mPosition;
    private viewHolder mHolder;
    double Lat1, Lng1, Lat2, Lng2;

    public getDistanceAsyncTask(int position, viewHolder holder, double lat1, double lng1, double lat2, double lng2) {
        mPosition = position;
        mHolder = holder;
        this.Lat1 = lat1;
        this.Lng1 = lng1;
        this.Lat2 = lat2;
        this.Lng2 = lng2;
    }

    @Override
    protected Object doInBackground(Object... params) {
        // TODO Auto-generated method stub

        String distanceST = "";
        Double dist = 0.0;
        String uri = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Lat1 + "," + Lng1 + "&destination=" + Lat2 + "," + Lng2 + "&mode=driving&sensor=false";
        String result = GET(uri);
        Log.d("result", "res=" + result);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(result.toString());
            JSONArray array = jsonObject.getJSONArray("routes");
            JSONObject routes = array.getJSONObject(0);
            JSONArray legs = routes.getJSONArray("legs");
            JSONObject steps = legs.getJSONObject(0);
            JSONObject distance = steps.getJSONObject("distance");

            distanceST = distance.getString("text");
            dist = Double.parseDouble(distanceST.replaceAll("[^\\.0123456789]", ""));

            // Utils.showToastMsg( HomeActivity.this, "Dist is :: " + dist );
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return distanceST;
    }

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

    }
}

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);
        else
            result = "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;
}

Please help if there is any best solution for this.

Preet_Android
  • 2,332
  • 5
  • 25
  • 43
  • What is slowing down the process ? The call to google api or the recovery of users location ? Probably using an async task in the getview is a BAD idea. This is call on every move in your list (I think) – AxelH Jul 01 '16 at 12:23
  • @AxelH, Yes call to google api slow down the app.. I agree that call api in getview is bad idea. So please suggest for any other solution.. – Preet_Android Jul 01 '16 at 12:27
  • This should be execute before it is pass to the listview. When you recover the list for the adapter. And running only one (or a few) async task and not on for each instance. It will take some time but if you manage to print **calculating** if no value is present in you holder, this could be user friendly – AxelH Jul 01 '16 at 13:27

1 Answers1

0

You can use android.location.Location class to calculate distance

Location.distanceBetween()

  • dear, its not giving the driving distance.. It gives the shortest path between given point.. – Preet_Android Jul 01 '16 at 12:04
  • **I need to find out the distance between two location in custom List View accurate and smoothly..** You asked for distance between location ... so he gave you the solution ;) – AxelH Jul 01 '16 at 12:18
  • It is not good idea, to load data from your adapter. Do you know all pairs, for which you should calculate the distance? – user2788843 Jul 01 '16 at 14:19
  • Yeah, it's clearly a wrong conception. The distance should be calculated before it is send to the adapter (at least, the task should be started) – AxelH Jul 01 '16 at 14:29