2013-08-19 100 views
27

我需要得到兩個位置之間的距離,但我需要像圖片中的藍線那樣獲得距離。 picure獲取android中兩個位置之間的距離?

下一個我嘗試:

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

,但我得到的紅線距離。

+0

嗨, 你不需要谷歌地圖在使用數學[http://www.movable-type.co.uk/scripts/latlong.html][1] 謝謝 – Felquir

+1

如果你想計算的路線,而不是紅線的距離比你將不得不使用谷歌API!這將返回距離和估計的時間來覆蓋距離! –

+0

它只是返回兩個位置的距離計算....如果你想紅線,然後使用Google API。 – Piyush

回答

31

使用Google Maps Directions API。您需要通過HTTP請求方向。您可以直接從Android或通過您自己的服務器執行此操作。從Montreal to Toronto

例如,方向:

GET http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false 

你會與一些JSON結束。在routes[].legs[].distance,你會得到一個對象是這樣的:

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

您也可以直接從響應對象獲取折線信息。

+0

嗨,你有什麼想法如何將公里轉換爲m仍然在JSON? –

0

試試這個:

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

希望這有助於。

+4

OP要藍線,而不是紅線。 – LuckyMe

10

由於克里斯布羅德福特是正確的,解析返回的JSON routes[].legs[].distance

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

用途:

final JSONObject json = new JSONObject(result); 
    JSONArray routeArray = json.getJSONArray("routes"); 
    JSONObject routes = routeArray.getJSONObject(0); 

    JSONArray newTempARr = routes.getJSONArray("legs"); 
    JSONObject newDisTimeOb = newTempARr.getJSONObject(0); 

    JSONObject distOb = newDisTimeOb.getJSONObject("distance"); 
    JSONObject timeOb = newDisTimeOb.getJSONObject("duration"); 

    Log.i("Diatance :", distOb.getString("text")); 
    Log.i("Time :", timeOb.getString("text")); 
+0

謝謝。你的代碼適合我。 –

2

使用:

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

您可以使用位置類的以下方法中的Android(如果u有經緯度,兩個位置的多頭)方法返回以米爲單位的大致距離。

公共靜態無效distanceBetween(雙startLatitude,雙startLongitude,雙endLatitude,雙endLongitude,浮法[]結果)

說明:

計算以米爲單位的兩個位置之間的近似距離,並任選地它們之間最短路徑的初始和最終方位。距離和方位使用WGS84橢球定義。

計算出的距離存儲在結果[0]中。如果結果長度大於或等於2,則初始方位將存儲在結果[1]中。如果結果長度爲3或更大,則最終方位將存儲在結果[2]中。 參數:

startLatitude - 起點緯度

startLongitude起始經度

endLatitude結束緯度

endLongitude結束經度

結果float數組中舉行結果

-1

試試這個代碼

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

您能解釋一下您的代碼如何根據OP得到藍線距離? –

-4

找出2點位置之間的距離:

  1. 當你第一次打開應用程序,進入到「時間軸」,從下拉菜單左上角。

  2. 打開新窗口後,從右上角菜單中的設置中選擇並選擇「添加位置」。

  3. 添加您的地點,並將它們命名爲點1,點2或任何易於記憶的名稱。

  4. 一旦您的地點被添加並標記,請返回到Google應用的主窗口。

  5. 點擊右下角帶有箭頭的藍色圓圈。

  6. 將打開一個新窗口,您可以在頂部看到有兩個文本字段,您可以在其中添加「從位置」和「距離位置」。

  7. 在點按在您保存的位置的任何文本字段,類型3

  8. 依次點擊文本字段,並添加你的下一個保存的位置。

  9. 通過這樣做,Google地圖將計算兩個位置之間的距離,並向您顯示地圖上的藍色路徑。

+0

問題是關於如何以編程方式在Android中找到兩點之間的距離。這個答案是錯誤的。 – Pang

+0

請提供代碼以回答問題 –

2
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; 
} 
+0

爲什麼您未傳遞參數「&key = YOUR_API_KEY」 – gaurang

相關問題