【问题标题】:How can we calculate distance between current location to lots of destination places in android?我们如何计算当前位置与android中许多目的地之间的距离?
【发布时间】:2014-05-20 22:25:12
【问题描述】:

我想计算两个位置之间的距离(即用户的当前位置和目标位置)。我的数据库和当前位置中有目的地的纬度和经度(我确实通过位置管理器类找到)。 我需要在列表视图中显示计算出的距离。 如果我通过 Location 类的任何 数学公式DistanceTo() 和 DistanceBetween() 方法计算它,那么我无法获得地图上的准确距离。 如果我通过谷歌的距离矩阵 API 计算距离,那么计算距离和加载列表需要花费太多时间。(因为有很多目的地位置只有一个用户当前位置) 请任何人建议我计算它的最佳方法.. 我从最近几天就陷入了这个问题..帮帮我 提前谢谢...

【问题讨论】:

  • 你好@Amiya..首先感谢您的支持。我已经尝试了五种方法- 1.DistanceTo() 2.Distance Between() 3.数学公式 4.Google Map API V3 5.Google Map API V2.现在 1 到 4 的问题没有得到正确的输出,而 Google API V2 需要花费大量时间,因为我一次计算距离用户当前位置近 100 个地方的距离,然后在列表视图中加载此距离。由于处理需要时间,我的列表视图无法正确滚动
  • DistanceTo() 和 DistanceBetween() 总是返回两个坐标之间的位移,这就是为什么你没有得到准确的结果。所以你可以做的是把你的其他数学公式放在 AsyncTask 中或使用线程来计算距离,只要确保你没有阻塞主线程。祝你好运!!!
  • @ANdroidGreek 谢谢。你能建议我对我有帮助的数学公式吗?我在calculateByDisplacement()下面试过了。

标签: android google-maps google-maps-api-3


【解决方案1】:

经过大量谷歌搜索后,我终于完成了我的任务。我通过异步任务尝试了它.. 这是我的代码..

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;

    }


 }  

参考链接是-

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

我不善于解释,但我正在尽力而为。希望它对像我这样的其他人有所帮助,因为我陷入了这项任务。

【讨论】:

    【解决方案2】:

    试试这个。我在我的旧应用程序中添加了这个。它对我有用。顺便说一下初始化R=Radius。仔细阅读this文章

     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;
       }
    

    【讨论】:

    • 嗯,谢谢,我已经尝试过,正如我上面提到的数学公式(因为我尝试过)。它在地图上提供不同的输出..
    • @kirtiHudda 请点击此链接stackoverflow.com/questions/22351984/…
    【解决方案3】:

    如果有很多位置,请使用循环。只需几行代码即可完成:

    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);
    

    【讨论】:

    • 完美答案:)
    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 2016-12-22
    • 2015-04-07
    • 2012-10-05
    • 2020-01-28
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    相关资源
    最近更新 更多