Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取android中两个位置之间的距离?_Android_Google Maps_Android Location - Fatal编程技术网

获取android中两个位置之间的距离?

获取android中两个位置之间的距离?,android,google-maps,android-location,Android,Google Maps,Android Location,我需要得到两个位置之间的距离,但我需要得到像图片中的蓝线一样的距离。 我尝试下一步: public double getDistance(LatLng LatLng1, LatLng LatLng2) { double distance = 0; Location locationA = new Location("A"); locationA.setLatitude(LatLng1.latitude); locationA.setLongitude(LatLn

我需要得到两个位置之间的距离,但我需要得到像图片中的蓝线一样的距离。

我尝试下一步:

public double getDistance(LatLng LatLng1, LatLng LatLng2) {
    double distance = 0;
    Location locationA = new Location("A");
    locationA.setLatitude(LatLng1.latitude);
    locationA.setLongitude(LatLng1.longitude);
    Location locationB = new Location("B");
    locationB.setLatitude(LatLng2.latitude);
    locationB.setLongitude(LatLng2.longitude);
    distance = locationA.distanceTo(locationB);

    return distance;
}
但我有红线距离。

试试这个:

private double calculateDistance(double fromLong, double fromLat,
            double toLong, double toLat) {
        double d2r = Math.PI / 180;
        double dLong = (toLong - fromLong) * d2r;
        double dLat = (toLat - fromLat) * d2r;
        double a = Math.pow(Math.sin(dLat / 2.0), 2) + Math.cos(fromLat * d2r)
                * Math.cos(toLat * d2r) * Math.pow(Math.sin(dLong / 2.0), 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = 6367000 * c;
        return Math.round(d);
    }

希望这有帮助。

因为Chris Broadfoot是正确的,所以要解析返回的JSON
routes[].legs[].distance

"legs" : [
        {
           "distance" : {
              "text" : "542 km",
              "value" : 542389
           }
使用:

使用。您需要通过HTTP请求指示。您可以直接从Android或通过您自己的服务器来完成此操作

例如,来自以下方面的说明:

您将得到一些JSON。在
routes[].legs[].distance
中,您将得到如下对象:

     "legs" : [
        {
           "distance" : {
              "text" : "542 km",
              "value" : 542389
           },
您还可以直接从响应对象获取多段线信息。

使用以下方法:

private String getDistanceOnRoad(double latitude, double longitude,
            double prelatitute, double prelongitude) {
        String result_in_kms = "";
        String url = "http://maps.google.com/maps/api/directions/xml?origin="
                + latitude + "," + longitude + "&destination=" + prelatitute
                + "," + prelongitude + "&sensor=false&units=metric";
        String tag[] = { "text" };
        HttpResponse response = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            response = httpClient.execute(httpPost, localContext);
            InputStream is = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(is);
            if (doc != null) {
                NodeList nl;
                ArrayList args = new ArrayList();
                for (String s : tag) {
                    nl = doc.getElementsByTagName(s);
                    if (nl.getLength() > 0) {
                        Node node = nl.item(nl.getLength() - 1);
                        args.add(node.getTextContent());
                    } else {
                        args.add(" - ");
                    }
                }
                result_in_kms = String.format("%s", args.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result_in_kms;
    }

您可以在android中使用Location类的以下方法(如果您有lat,两个位置的long),该方法返回以米为单位的近似距离

public static void distance-between(双起点、双起点、双终点纬度、双终点经度、float[]结果)

说明:

计算两个位置之间的近似距离(以米为单位),以及它们之间最短路径的初始方位角和最终方位角(可选)。使用WGS84椭球定义距离和方位

计算的距离存储在
结果[0]
中。如果结果的长度大于等于2,则初始轴承将存储在
results[1]
中。如果结果长度大于等于3,则最终轴承将存储在
results[2]
中。 参数:

起始纬度

起始经度

结束纬度结束纬度

结束经度结束经度

结果用于保存结果的浮点数组

试试这个代码

public double CalculationByDistance(LatLng StartP, LatLng EndP) {
    int Radius = 6371;// radius of earth in Km
    double lat1 = StartP.latitude;
    double lat2 = EndP.latitude;
    double lon1 = StartP.longitude;
    double lon2 = EndP.longitude;
    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));
    double valueResult = Radius * c;
    double km = valueResult / 1;
    DecimalFormat newFormat = new DecimalFormat("####");
    int kmInDec = Integer.valueOf(newFormat.format(km));
    double meter = valueResult % 1000;
    int meterInDec = Integer.valueOf(newFormat.format(meter));
    Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
            + " Meter   " + meterInDec);

    return Radius * c;
}

要查找两个位置之间的距离,请执行以下操作:

  • 当你第一次打开应用程序时,从左上角的下拉菜单转到“你的时间线”

  • 新窗口打开后,从右上角菜单上的设置中选择,然后选择“添加位置”

  • 添加您的位置,并将其命名为点1、点2或任何易于记住的名称

  • 添加并标记位置后,返回Google应用程序的主窗口

  • 单击右下角有箭头的蓝色圆圈

  • 将打开一个新窗口,您可以看到顶部有两个文本字段,您可以在其中添加“起始位置”和“距离位置”

  • 单击任何文本字段并在第3点中键入保存的位置

  • 单击另一个文本字段并添加下一个保存的位置

  • 通过这样做,谷歌地图将计算两个位置之间的距离,并在地图上显示蓝色路径


  • 您可以使用任何距离API。GoogleAPI是最流行的API之一,但也有一些替代方案,如

    它非常容易使用,因为如果您以前习惯使用GoogleMapsAPI,就不需要重写代码

    以下是请求的一个示例:

    Get: https://api.distancematrix.ai/distancematrix?origins=51.4822656,-0.1933769&destinations=51.4994794,-0.1269979&key=<your_access_token>
    

    免责声明:我在一家创建此API的公司工作。

    您好,您不需要谷歌地图来使用它[谢谢如果你想计算路线的距离而不是红线,那么你就必须使用谷歌api!它将返回你的距离和估计到达距离的时间!它只返回两个位置的距离计算结果……如果你想使用红线,那么就使用谷歌api。OP想要的是蓝线,而不是红线。你能请解释一下你的代码是如何根据OP得到蓝线距离的?问题是如何通过编程在Android中找到两点之间的距离。这个答案是错误的。为什么你不传递参数“&key=your_API_key”嗨,你知道如何将km转换为仍然使用JSON的m吗?不幸的是,“不推荐使用谷歌地图平台的无钥匙访问”。请更新您的答案。此外,它现在必须使用HTTPS,这将从直线角度返回一个值。我认为这不是OP的意图。不管怎样,这是一个很棒的方法;-)。
    public double CalculationByDistance(LatLng StartP, LatLng EndP) {
        int Radius = 6371;// radius of earth in Km
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        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));
        double valueResult = Radius * c;
        double km = valueResult / 1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec = Integer.valueOf(newFormat.format(km));
        double meter = valueResult % 1000;
        int meterInDec = Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
                + " Meter   " + meterInDec);
    
        return Radius * c;
    }
    
    private String getDistance(double lat2, double lon2){
        Location loc1 = new Location("A");
        loc1.setLatitude("A1");
        loc1.setLongitude("B1");
        Location loc2 = new Location("B");
        loc2.setLatitude(lat2);
        loc2.setLongitude(lon2);
        float distanceInMeters = loc1.distanceTo(loc2);
        float mile = distanceInMeters / 1609.34f;
        String sm = String.format("%.2f", mile);
        return sm;
    }
    
    public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
        String parsedDistance;
        String response;
    
        Thread thread=new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
              final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              conn.setRequestMethod("POST");
              InputStream in = new BufferedInputStream(conn.getInputStream());
              response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
    
              JSONObject jsonObject = new JSONObject(response);
              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");
              parsedDistance=distance.getString("text");
            } catch (ProtocolException e) {
              e.printStackTrace();
            } catch (MalformedURLException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
    
        thread.start();
    
        try {
          thread.join();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    
        return parsedDistance;
    }
    
    Get: https://api.distancematrix.ai/distancematrix?origins=51.4822656,-0.1933769&destinations=51.4994794,-0.1269979&key=<your_access_token>
    
    {
      "destination_addresses":["Westminster Abbey, Westminster, 
      London SW1P 3PA, UK"],
      "origin_addresses":["Chapel, Fulham, London SW6 1BA, UK"],
      "rows":[
        {
          "elements":[
            {
              "distance":{
                "text": "4.7 miles",
                "value": 7563.898
              },
              "duration":{
                "text": "28 min",
                "value": 1680
              },
              "duration_in_traffic":{
                "text": "28 min",
                "value": 1680
              },
              "status": "OK"
            }
          ]
        }
      ],
      "status": "OK"
    }