【问题标题】:Distance between 2 places on Android MapAndroid地图上2个地方之间的距离
【发布时间】:2016-09-11 02:28:54
【问题描述】:

我需要计算当前位置和目的地之间的距离。我有当前和目的地位置的纬度和经度。我在搜索时从 SO 和 Internet 中找到了以下代码。但是计算给出了 1366 公里,而谷歌地图给出了 2 个位置之间的 1675 公里。有人可以帮助我如何计算准确的距离。目的地遍布全球,包括我目前所在的城市位置。

//Distance in Kilometers
    fun distanceInKms ( lat1: Double, long1: Double, lat2: Double, long2: Double) : Double
    {
        val degToRad= Math.PI / 180.0;
        val phi1 = lat1 * degToRad;
        val phi2 = lat2 * degToRad;
        val lam1 = long1 * degToRad;
        val lam2 = long2 * degToRad;

        return 6371.01 * Math.acos( Math.sin(phi1) * Math.sin(phi2) + Math.cos(phi1) * Math.cos(phi2) * Math.cos(lam2 - lam1) );
    }

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您要直线距离,还是要曲面距离(圆弧、曲线)?
  • 精确距离是什么意思?

标签: android android-location


【解决方案1】:

使用 android.location.Location 类,从 Android 的 API 级别 1 开始可用。它有一个静态的distanceBetween 方法为你做这一切。

见: http://developer.android.com/reference/android/location/Location.html

float[] results = new float[1];
android.location.Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
    //distance in meters now in results[0]

除以 1000 以公里 (km) 为单位。

【讨论】:

  • 我使用了 distanceTo 但同样的问题
  • 您是否使用了非十进制度格式?因为这些肯定是正确的。
  • 或者你是如何使用谷歌地图计算的?可能是道路/汽车距离。
【解决方案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;
    }

【讨论】:

  • 距离是公里吗?
  • 不。 abv 计算得出 1366。lat 和 long 都是 -37.5931551,144.7216202,-27.485572,153.038064。计算并查看
  • 检查您的坐标是否正确。这对我来说非常适合(我的应用程序)可能是您在地图上选择了错误的坐标
【解决方案3】:

你可以使用它,就像谷歌别忘了添加互联网权限

      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 + "&mode=driving&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<String> args = new ArrayList<String>();
                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;
    }

这个库有类来获取时间、距离和在 2 个地方之间绘制折线,它像谷歌地图一样工作 https://github.com/memo1231014/MUT-master

库示例

    RouteInformations rInformation = new RouteInformations(new     AsyncResponse() {

            @Override
            public void processFinish(RouteDetails arg0) {
                // TODO Auto-generated method stub
                try
                {
                  map.addPolyline(arg0.getLineOptions()); //you can add the return line and add it to the map 

                  //here you can get distance , duration it will return like you drive a car 
                  MUT.fastDialog(Map.this,"Time and Distance","Distance : "+arg0.getDistance()+"\nDuration : "+arg0.getDuration());
              }
                catch(Exception e)
                {
                    MUT.lToast(Map.this,"Can't draw line Try Again");
                }
                }
        });

        //you should pass the 2 lat and lang which you want to draw a aline or get distance or duration between them 
         RouteDetails routeDetails=new RouteDetails();
        routeDetails.setLatLong1(from.getPosition());
        routeDetails.setLatLong2(to.getPosition());
        rInformation.execute(routeDetails);

【讨论】:

    猜你喜欢
    • 2016-07-08
    • 2010-11-09
    • 1970-01-01
    • 2013-04-23
    • 2018-01-13
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多