gpt4 book ai didi

java - 查找出发地 LatLng 和目的地 LatLng 之间的行驶距离

转载 作者:太空宇宙 更新时间:2023-11-04 14:13:37 37 4
gpt4 key购买 nike

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

Invalid float: ""

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

Button On Click

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

Handler

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

最佳答案

是否有可能您的 locationAddress 为空,导致您的 parseFloat 调用在 Handler 中具有空字符串参数,或者您的 Float.valueOf 参数在 getDistance 中为空?

编辑您现在已向您的问题添加了堆栈跟踪。这清楚地指向 getDistance 中的 Float.valueOf 参数。

始终测试您对 valueOfparseInt 等方法的输入是否为 null、空或无效字符串 - 这样您就可以避免抛出异常。一种方法是:

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

您将遇到的另一个问题是,在 Handler 中,您的默认 switch case 设置 locationAddress = null;。当您调用 String splitLocation[] = locationAddress.split(","); 时,它会给您一个 NullPointerException

关于java - 查找出发地 LatLng 和目的地 LatLng 之间的行驶距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28000868/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com