在Android中计算我当前位置到目的地位置的距离

13

我必须制作一个项目,需要计算从我的位置到目标位置的距离,并在文本视图中显示。请注意,当我的位置发生变化时,该距离会更新。是否可以制作这样类型的项目?

[备注:不使用Google地图进行实现。目标经度,纬度已知。只需找到我的位置并进行计算]

4个回答

16

查看Google Android开发页面上的文档,以了解如何监听位置更改。 http://developer.android.com/guide/topics/location/obtaining-user-location.html

您可以使用此函数确定当前(起始)点与目标点之间的距离。

 /**
 * using WSG84
 * using the Metric system
 */
public static float getDistance(double startLati, double startLongi, double goalLati, double goalLongi){
    float[] resultArray = new float[99];
    Location.distanceBetween(startLati, startLongi, goalLati, goalLongi, resultArray);
    return resultArray[0];
}

1
当获得一个新位置时(参见上面的链接),您可以开始一个新的AsyncTask。在onPostExecute方法中,您可以将距离写入TextView中。 - CAA
1
但是怎么做呢?对不起,我在安卓方面是新手。你能在这里解释一下或者给我提供一段代码来显示在TextView中吗? - MBMJ
2
你需要创建一个监听器(参见链接)。在onLocationChanged()方法中,你需要执行一个新的AsyncTask。这个任务需要引用textview(-> findViewById())。在任务的doInBackground()方法中,你需要计算距离,在onPostExecute()方法中,你需要设置textview的文本。也许有更优雅的方法来实现这个功能,但它可以工作 :) - CAA
如果您想要以公里为单位返回结果,例如“return resultArray [0] / 1000;”,请将结果除以1000。 - Ramkesh Yadav

12

Location.distanceBetween会给出两点之间的直线距离。如果你想要两个地理点之间路径的距离,那么可以使用这个类来实现:

public class GetDistance {

public String GetRoutDistane(double startLat, double startLong, double endLat, double endLong)
{
  String Distance = "error";
  String Status = "error";
  try {
      Log.e("Distance Link : ", "http://maps.googleapis.com/maps/api/directions/json?origin="+ startLat +","+ startLong +"&destination="+ endLat +","+ endLong +"&sensor=false");
        JSONObject jsonObj = parser_Json.getJSONfromURL("http://maps.googleapis.com/maps/api/directions/json?origin="+ startLat +","+ startLong +"&destination="+ endLat +","+ endLong +"&sensor=false"); 
        Status = jsonObj.getString("status");
        if(Status.equalsIgnoreCase("OK"))
        {
        JSONArray routes = jsonObj.getJSONArray("routes"); 
         JSONObject zero = routes.getJSONObject(0);
         JSONArray legs = zero.getJSONArray("legs");
         JSONObject zero2 = legs.getJSONObject(0);
         JSONObject dist = zero2.getJSONObject("distance");
         Distance = dist.getString("text");
        }
        else
        {
            Distance = "Too Far";
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
return Distance;


} 

这将为您提供两个点之间的距离或道路长度。

这里是解析JSON api的parser_Json类

 public class parser_Json {

public static JSONObject getJSONfromURL(String url){

    //initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    }catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //convert response to string
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
    }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
    }

    //try parse the string to a JSON object
    try{
            jArray = new JSONObject(result);
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return jArray;
}

 public static InputStream retrieveStream(String url) {

        DefaultHttpClient client = new DefaultHttpClient(); 

        HttpGet getRequest = new HttpGet(url);

        try {

           HttpResponse getResponse = client.execute(getRequest);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 

              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();
           return getResponseEntity.getContent();

        } 
        catch (IOException e) {
           getRequest.abort();

        }

        return null;

     }

}

:闭合一个 HTML 段落标签。

4
我在这个问题中写了两个不同的答案来计算两个地理点之间的差异,因此不在此处复制粘贴。
其次,请参见此示例,以相同的方式实现Locationlistener以获取onLocationChanged事件。
然后,在该事件中使用上述给定函数计算差异并适当使用它们。

3

使用 LocationServices 可以很容易地确定您的位置,并在每次接收到更新时更新您的 TextView 显示新的距离。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接