我在显示JsonObject
从Google返回的距离和位置时遇到问题。我可以获取两点之间的位置和路线,但是无法在TextView
中显示距离和位置。
我只能使用
Log.d("distance", "Calculated distance:" + dist + " km ");
,但无法通过textview
/ Toast
显示。我知道也有类似的问题,但仍然无法解决我的问题。
DirectionJsonParser.java
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
long totalDistance = 0;
int totalSeconds = 0;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
totalDistance = totalDistance + Long.parseLong(jDistance.getString("value"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
totalSeconds = totalSeconds + Integer.parseInt(jDuration.getString("value"));
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List list = decodePoly(polyline);
/** Traversing all points */
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
double dist = totalDistance / 1000.0;
Log.d("distance", "Calculated distance:" + dist + " km ");
int days = totalSeconds / 86400;
int hours = (totalSeconds - days * 86400) / 3600;
int minutes = (totalSeconds - days * 86400 - hours * 3600) / 60;
int seconds = totalSeconds - days * 86400 - hours * 3600 - minutes * 60;
Log.d("duration", days + " days " + hours + " hours " + minutes + " mins " + seconds + " seconds ");
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
TextView
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="DISTANCE"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="@android:color/holo_red_dark"
android:id="@+id/display_distance"/>
<TextView
android:id="@+id/display_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="DURATION"
android:textColor="@android:color/holo_red_dark"
android:textSize="20sp"
android:textStyle="bold" />
TrackingOrder.java
TextView distance,duration;
distance = (TextView)findViewById(R.id.display_distance);
duration = (TextView)findViewById(R.id.display_duration);
private void drawRoute(final LatLng yourLocation, final Request request) {
//clear all polyline
if (polyline != null)
polyline.remove();
if (request.getAddress() != null && !request.getAddress().isEmpty()) {
mService.getGeoCode(request.getAddress()).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
String lat = ((JSONArray) jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lat").toString();
String lng = ((JSONArray) jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lng").toString();
final LatLng orderLocation = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.deliverybox);
bitmap = Common.scaleBitmap(bitmap, 70, 70);
MarkerOptions marker = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.title("Order of " + Common.currentRequest.getPhone())
.position(orderLocation);
mMap.addMarker(marker);
//draw route
mService.getDirections(yourLocation.latitude + "," + yourLocation.longitude,
orderLocation.latitude + "," + orderLocation.longitude)
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
new ParserTask().execute(response.body().toString());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
ProgressDialog mDialog = new ProgressDialog(TrackingOrder.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.setMessage("Please waiting...");
mDialog.show();
}
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jsonObject;
List<List<HashMap<String, String>>> routes = null;
try {
jsonObject = new JSONObject(strings[0]);
DirectionJSONParser parser = new DirectionJSONParser();
routes = parser.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
mDialog.dismiss();
ArrayList points = null;
PolylineOptions lineOptions = null;
for (int i = 0; i < lists.size(); i++) {
points = new ArrayList();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = lists.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
}
mMap.addPolyline(lineOptions);
}
答案 0 :(得分:0)
生成一个名称为public class Constant {
public static String DISTANCE= "";
public static String DURATION= "";
}
的Java类,并像这样初始化两个可变的距离和持续时间
DirectionJsonParser.java
现在进入您的 double dist = totalDistance / 1000.0;
Constant.DISTANCE = String.valueof(dist); //CHECK HERE
Log.d("distance", "Calculated distance:" + dist + " km ");
int days = totalSeconds / 86400;
int hours = (totalSeconds - days * 86400) / 3600;
int minutes = (totalSeconds - days * 86400 - hours * 3600) / 60;
int seconds = totalSeconds - days * 86400 - hours * 3600 - minutes * 60;
Constant.DURATION= String.valueof(days + " days " + hours + " hours " + minutes + " mins " + seconds + " seconds "); //CHECK HERE
Log.d("duration", days + " days " + hours + " hours " + minutes + " mins " + seconds + " seconds ");
TrackingOrder
在您的distance.setText(Constant.DISTANCE);
duration.setText(Constant.DURATION);
0: {…}
_attachmentNames: null
_conversation: Object { _id: 33, _subject: "Mail subject", _oldestMessageDate: null, … }
_conversationID: 33
_date: Date 2018-11-10T18:36:17.000Z
_folderID: 10
_headerMessageID: "2406fd77c38de6911ad0d132b.8e1e26680d.20181110183544.00d1a6581a.944a07b4@mail99.wdc01.mcdlv.net"
_id: 72
_indexedBodyText: //Mail Body here
_messageKey: 2596
_notability: 25
_subject: //Mail subject
attachmentInfos: Array []
bcc: Array []
cc: Array []
forwarded: false
from: Object { _id: 16, _contactID: 15, _kind: "email", … }
involves: Array [ {…}, {…} ]
isEncrypted: false
read: true
recipients: Array [ {…} ]
repliedTo: false
starred: true
tags: Array []
to: Array [ {…} ]
toMe: Array [ (2) […] ]
<prototype>: Object { NOUN_ID: 102, _datastore: {…}, id: Getter, … }