在android中,我们如何计算当前位置到许多目的地之间的距离?

在android中,我们如何计算当前位置到许多目的地之间的距离?,android,google-maps,google-maps-api-3,Android,Google Maps,Google Maps Api 3,我想计算两个位置之间的距离(即用户的当前位置和目的地位置)。我在数据库中有目的地的纬度和经度以及当前位置(我通过location Manager类查找)。 我需要在列表视图中显示计算出的距离。 如果我用Location类的任何数学公式或DistanceTo()和DistanceBetween()方法计算它,那么我就不能得到地图上的精确距离。 如果我用谷歌的distance Matrix API计算距离,那么计算距离和加载列表会花费太多时间。(因为有很多目的地都有一个用户的当前位置) 请告诉我最好

我想计算两个位置之间的距离(即用户的当前位置和目的地位置)。我在数据库中有目的地的纬度和经度以及当前位置(我通过location Manager类查找)。 我需要在列表视图中显示计算出的距离。 如果我用Location类的任何数学公式DistanceTo()和DistanceBetween()方法计算它,那么我就不能得到地图上的精确距离。 如果我用谷歌的distance Matrix API计算距离,那么计算距离和加载列表会花费太多时间。(因为有很多目的地都有一个用户的当前位置) 请告诉我最好的计算方法。。 这几天来我一直在这个问题上..帮帮我
提前感谢…

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

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

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

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

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

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;

    }


 }  
public View getView(int位置、视图转换视图、视图组父视图)
{
最终视图持有者=新的视图持有者();
视图=转换视图;
如果(视图==null){
convertView=充气机。充气(R.layout.layout_行,空);
}
holder.textdistance=(TextView)convertView.findViewById(R.id.TextView\u距离);
holder.position=位置;

if(data.size()经过大量的谷歌搜索,我终于完成了我的任务。我尝试了异步任务。。 这是我的密码

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;

    }


 }  
public View getView(int位置、视图转换视图、视图组父视图)
{
最终视图持有者=新的视图持有者();
视图=转换视图;
如果(视图==null){
convertView=充气机。充气(R.layout.layout_行,空);
}
holder.textdistance=(TextView)convertView.findViewById(R.id.TextView\u距离);
holder.position=位置;

if(data.size()如果有许多位置,请使用循环。只有几行代码可以完成此操作:

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

如果有多个位置,请使用循环。只有几行代码可以完成此操作:

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

查看此链接Hello@Amiya..首先感谢您的支持。我已经尝试了五种方法-1.距离()2.距离()3.数学公式4.谷歌地图API V3 5.谷歌地图API V2.现在1到4的问题是没有得到正确的输出,而谷歌API V2的问题是它需要很多时间,因为我一次计算距离用户当前位置近100个位置的距离,然后将此距离加载到列表视图中。由于处理我的列表视图未滚动到properlyDistanceTo()和DistanceBetween()始终返回两个坐标之间的位移,这就是为什么不能得到准确的结果。因此,您可以将其他数学公式放在AsyncTask中或使用线程来计算距离,只需确保您没有阻塞主线程。祝您好运!!!!@ANdroidGreek谢谢。您能建议我数学公式吗las对我有帮助吗?我已经尝试了下面的calculateByDisplacement()…但它没有用..检查此链接Hello@Amiya..首先感谢您的支持。我已经尝试了五种方法-1.DistanceTo()2.DistanceTo()3.数学公式4.谷歌地图API V3 5.谷歌地图API V2.现在1到4的问题是没有得到正确的输出,而谷歌API V2的问题是它需要很多时间,因为我一次计算距离用户当前位置近100个位置的距离,然后将此距离加载到列表视图中。由于处理我的列表视图未滚动到properlyDistanceTo()和DistanceBetween()始终返回两个坐标之间的位移,这就是为什么不能得到准确的结果。因此,您可以将其他数学公式放在AsyncTask中或使用线程来计算距离,只需确保您没有阻塞主线程。祝您好运!!!!@ANdroidGreek谢谢。您能建议我数学公式吗las对我有帮助吗?我试过下面的calculateByDisplacement()…但它没有用..好吧,谢谢,我已经试过了,因为我提到了上面的数学公式(我也试过了)。它通过地图上的输出给出不同的输出。@kirtiHudda请遵循此链接。谢谢,我已经尝试过了,因为我提到了上面的数学公式(我也尝试过)。它通过地图上的输出给出不同的输出。@kirtiHudda请遵循此链接完美答案:)完美答案:)