找到起始LatLng和目标LatLng之间的行驶距离

时间:2015-01-17 15:15:40

标签: java android google-maps

我有一项任务是找到两个纬度和经度坐标之间的行驶距离。我找到了这个链接[这里] [1]但是,我不确定我是否正确实现它,因为我收到错误....

  

无效的浮动:“”

GeocodingLocation.java

public class GeocodingLocation {

    private static final String TAG = "GeocodingLocation";

    public static void getAddressFromLocation(final String locationAddress,
                                              final Context context, final Handler handler) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String endPosition = null;
                try {
                    List
                            addressList = geocoder.getFromLocationName(locationAddress, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = (Address) addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        sb.append(address.getLatitude()).append("\n,");
                        sb.append(address.getLongitude()).append("\n");
                        endPosition = sb.toString();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable to connect to Geocoder", e);
                } finally {
                    Message message = Message.obtain();
                    message.setTarget(handler);
                    if (endPosition != null) {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        endPosition = endPosition;
                        bundle.putString("address", endPosition);
                        message.setData(bundle);
                    }
                    else {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        endPosition = "Address: " + locationAddress +
                                "\n Unable to get Latitude and Longitude for this address location.";
                        bundle.putString("address", endPosition);
                        message.setData(bundle);
                    }
                    message.sendToTarget();
                }
            }
        };
        thread.start();
    }
}
  

按钮单击

public void onClick_btnLocate(View v){
    try {
        String address = tbStreet.getText().toString() + " "
                + tbCity.getText().toString() + " "
                + spinStates.getSelectedItem().toString() + " "
                + tbZip.getText().toString();


        GeocodingLocation locationAddress = new GeocodingLocation();
        locationAddress.getAddressFromLocation(address,
                getApplicationContext(), new GeocoderHandler());


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

处理程序

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String locationAddress;

        switch (message.what) {
            case 1:
                Bundle bundle = message.getData();
                locationAddress = bundle.getString("address");
                break;
            default:
               locationAddress = null;
        }


        String splitLocation[] = locationAddress.split(",");
        Float lat2 = Float.parseFloat(splitLocation[0]);
        Float lon2 = Float.parseFloat(splitLocation[1]);
        Float lat1 = Float.parseFloat("39.055564880371094");
        Float lon1 = Float.parseFloat("-84.65643310546875");
        LatLng latLngDest = new LatLng(lat2, lon2);
        LatLng latLngStart = new LatLng(39.055564880371094, -84.65643310546875);

        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLngDest, 10);
        map.addMarker(new MarkerOptions().position(latLngStart).title("Begin Here"));
        map.addMarker(new MarkerOptions().position(latLngDest).title("Take Me Here!"));
        map.animateCamera(update);
        tvLongitude.setText(latLngDest.toString());

        getDistance(lat1, lon1, lat2, lon2);

    }
}
  

getDistance的

public float getDistance(float lat1, float lon1, float lat2, float lon2) {
     String result_in_kms = "";
     String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&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.valueOf( args.get(0));
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
      Float f=Float.valueOf(result_in_kms); //error occurs here, lat lngs are never passed?

      tvLatitude.setText(f.toString()); 

      return f*1000;

  }

非常感谢任何帮助!

  

logcat的

01-17 10:05:49.606  29336-29336/com.magtek.mobile.android.scra.MagTekDemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.magtek.mobile.android.scra.MagTekDemo, PID: 29336
    java.lang.NumberFormatException: Invalid float: ""
            at java.lang.StringToReal.invalidReal(StringToReal.java:63)
            at java.lang.StringToReal.parseFloat(StringToReal.java:308)
            at java.lang.Float.parseFloat(Float.java:306)
            at java.lang.Float.valueOf(Float.java:343)
            at com.magtek.mobile.android.scra.MagTekDemo.SelectZone.getDistance(SelectZone.java:164)
            at com.magtek.mobile.android.scra.MagTekDemo.SelectZone$GeocoderHandler.handleMessage(SelectZone.java:129)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

  [1]: http://stackoverflow.com/questions/22609087/how-to-find-distance-by-road-between-2-geo-points-in-android-application-witho

1 个答案:

答案 0 :(得分:0)

您的locationAddress是否为空,以致您的parseFloat调用在Handler中有空字符串参数,或Float.valueOf参数在getDistance中为空?< / p>

编辑您现在已经为您的问题添加了堆栈跟踪。这显然指向Float.valueOf中的getDistance参数。

始终测试对valueOfparseInt等方法的输入,以获取null,空或无效字符串 - 这样可以避免引发的异常。一种方法是:

if (input != null && input.length() > 0) { ... }

您将遇到的另一个问题是Handler您的默认开关案例集locationAddress = null;。当您致电String splitLocation[] = locationAddress.split(",");时,它会为您提供NullPointerException