【问题标题】:Distance between two location in Android mapAndroid地图中两个位置之间的距离
【发布时间】:2012-08-31 11:35:19
【问题描述】:

如何计算 android 地图中两个位置之间的距离 & 输出必须显示在 textview 或任何中?

【问题讨论】:

标签: android android-mapview


【解决方案1】:

我认为您需要 googleapi,我以前使用过此类服务.. 您可以获取从当前位置到目的地的距离。

只需 uee 以下网址:

http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false&mode=driving

这里,原点=%f,%f = 原点=纬度,经度 目的地=%f,%f = 目的地=纬度,经度

谷歌回复:

{

    "routes": [
        {
            "bounds": {
                "northeast": { … },
                "southwest": { … }
            },
            "copyrights": "Map data ©2012 Inav/Geosistemas SRL",
            "legs": [
                {
                    "distance": {
                        "text": "1 m",
                        "value": 0
                    },
                    "duration": { … },
                    "end_address": "Formosa Province, Argentina",
                    "end_location": { … },
                    "start_address": "Formosa Province, Argentina",
                    "start_location": { … },
                    "steps": [ … ],
                    "via_waypoint": [ ]
                }
            ],
            "overview_polyline": { … },
            "summary": "RP 3",
            "warnings": [ ],
            "waypoint_order": [ ]
        }
    ],
    "status": "OK"

}

上面你可以看到

"distance": {
                            "text": "1 m",
                            "value": 0
                        },

还有你的距离:

代码可能如下所示:

private void getDistance(){
StringBuffer jsonString = new StringBuffer();

        httpPost = new HttpPost("http://maps.googleapis.com/maps/api/directions/json?origin=<latitude>,<longitude>&destination=<latitude>,<longitude>&sensor=false&mode=driving");


        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            httpResponse = httpClient.execute(httpPost);

            InputStream in = httpResponse.getEntity().getContent();
            int ch = 0;
            while ((ch = in.read()) != -1) {
                jsonString.append((char) ch);
            }
            in.close();

            JSONObject jsonObject = new JSONObject(jsonString.toString());
            JSONArray jsonArray = jsonObject.getJSONArray(""legs");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jObj = jsonArray.getJSONObject(i);

                String text = jObj.getString("text");
                String value = jObj.getString("value");//value is ur distance
            }



        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

希望有帮助。

【讨论】:

  • 如果你有,可以举个例子。
  • 它真的很简单。如果你知道 JSON 解析。只需使用您的源和目标位置点击上面的 URL。作为回应,谷歌会给你一个 JSON 对象,它在两个位置之间有一个距离。
【解决方案2】:
textView.setText(""+location1.distanceTo(location2));

【讨论】:

    【解决方案3】:

    对于像我这样正在学习/迟到的人。使用了下面@NaserShaikh 编写的代码。 当你有纬度、经度两点时,你可以在这里找到一个工作代码来获取谷歌地图上的行驶距离!!距离以英里为单位! 有更好的方法来解析 JSON 响应请寻找它。 当有海洋 btw 和其他东西时,Havent 对其进行了极端测试。希望对您有所帮助。

    package havefun;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    class Distance {
        private Double dist;
        public Distance() {
            dist = (double) -1;
    
        }
    
        private Double getDistance(){
            StringBuffer jsonString = new StringBuffer();
    
                  HttpPost  httpPost = new HttpPost("http://maps.googleapis.com/maps/api/directions/json?origin=<src_lat>,<src_long>&destination=<dst_lat>,<dst_long>&sensor=false&mode=driving");
    
                  CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                    try {
    
                     CloseableHttpResponse HttpResponse = httpClient.execute(httpPost);
    
                        InputStream in = HttpResponse.getEntity().getContent();
    
                        int ch = 0;
                        while ((ch = in.read()) != -1) {
                            jsonString.append((char) ch);
                        }
                        in.close();
    
    
                        JSONObject jsonObject = new JSONObject(jsonString.toString());
                        //System.out.println(jsonObject);
                        //System.out.println("========================");
                        //System.out.println(jsonObject.get("status"));
                        if (jsonObject.get("status").toString().equals("OK") == false) {
                            System.err.println("Error");
                            return dist;
                        }
    
                        String distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
    
                        System.out.println(distance);
    
                        String temp[] = distance.split(" ");
                        System.out.println(temp[1]);
                        System.out.println(temp[0]);
    
                        dist = Double.parseDouble(temp[0]);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return dist;
    
            }
    
    
        public static void main(String[] args) {
            Distance d = new Distance();
                Double dist = d.getDistance();
                System.out.println("Distance ="+dist);
        }
    }
    

    【讨论】:

      【解决方案4】:
      /**
       * Calculate the distance between 2 points based on their GeoPoint coordinates. <br>
       * Return the value in Km or miles based on the unit input
       * @param gp1 (GeoPoint): First point.
       * @param gp2 (GeoPoint): Second point.
       * @param unit (char): Unit of measurement: 'm' for miles and 'k' for Km.
       * @return (double): The distance in miles or Km.
       */
      public static double getDistance(GeoPoint gp1, GeoPoint gp2, char unit)
      {
          //Convert from degrees to radians
          final double d2r = Math.PI / 180.0;
      
          //Change lat and lon from GeoPoint E6 format
          final double lat1 = gp1.getLatitudeE6() / 1E6;
          final double lat2 = gp2.getLatitudeE6() / 1E6;
          final double lon1 = gp1.getLongitudeE6() / 1E6;
          final double lon2 = gp2.getLongitudeE6() / 1E6;
      
          //The difference between latitudes and longitudes
          double dLat = Math.abs(lat1 - lat2) * d2r;
          double dLon = Math.abs(lon1 - lon2) * d2r;
      
          double a = Math.pow(Math.sin(dLat / 2.0), 2) 
                  + Math.cos(lat1 * d2r) * Math.cos(lat2 * d2r)
                  * Math.pow(Math.sin(dLon / 2.0), 2);
      
          double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      
          //Return the distance
          return (unit == 'm' ? 3956 : 6367) * c;
      } //End getDistance()
      
      
      TextView textView.setText("" + getDistance(gp1, gp2, 'k'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-21
        • 1970-01-01
        • 1970-01-01
        • 2011-12-24
        • 2016-02-27
        • 1970-01-01
        相关资源
        最近更新 更多