android get duration from maps.google.com directions - java

At the moment I am using this code to inquire google maps for directions from an address to another one, then I simply draw it on a mapview from its GeometryCollection. But yet this isn't enough I need also to extract the total expected duration from the kml. can someone give a little sample code to help me? thanks
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");//from
urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
urlString.append("&daddr=");//to
urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
urlString.append("&ie=UTF8&0&om=0&output=kml");
//Log.d("xxx","URL="+urlString.toString());
// get the kml (XML) doc. And parse it to get the coordinates(direction route).
Document doc = null;
HttpURLConnection urlConnection= null;
URL url = null;
try
{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
{
//String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
//Log.d("xxx","path="+ path);
String[] pairs = path.split(" ");
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
// src
GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for(int i=1;i<pairs.length;i++) // the last one would be crash
{
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
//Log.d("xxx","pair:" + pairs[i]);
}
mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (SAXException e){
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}

Use the new Directions api. The duration is returned in the response and no more parsing of KML, which I think breaks the Google maps license terms anyways.
Update. Ok use the JSON output, with it parsing is built into Android.
Ex url
Response is
{
"status": "OK",
"routes": [ {
"summary": "I-40 W",
"legs": [ {
"steps": [ {
"travel_mode": "DRIVING",
"start_location": {
"lat": 41.8507300,
"lng": -87.6512600
},
"end_location": {
"lat": 41.8525800,
"lng": -87.6514100
},
"polyline": {
"points": "a~l~Fjk~uOwHJy#P",
"levels": "B?B"
},
"duration": {
"value": 19,
"text": "1 min"
},
"html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e",
"distance": {
"value": 207,
"text": "0.1 mi"
}
},
...
... additional steps of this leg
...
... additional legs of this route
"duration": {
"value": 74384,
"text": "20 hours 40 mins"
},
"distance": {
"value": 2137146,
"text": "1,328 mi"
},
"start_location": {
"lat": 35.4675602,
"lng": -97.5164276
},
"end_location": {
"lat": 34.0522342,
"lng": -118.2436849
},
"start_address": "Oklahoma City, OK, USA",
"end_address": "Los Angeles, CA, USA"
} ],
"copyrights": "Map data ©2010 Google, Sanborn",
"overview_polyline": {
"points": "a~l~Fjk~uOnzh#vlbBtc~#tsE`vnApw{A`dw#~w\\|tNtqf#l{Yd_Fblh#rxo#b}#xxSfytAblk#xxaBeJxlcBb~t#zbh#jc|Bx}C`rv#rw|#rlhA~dVzeo#vrSnc}Axf]fjz#xfFbw~#dz{A~d{A|zOxbrBbdUvpo#`cFp~xBc`Hk#nurDznmFfwMbwz#bbl#lq~#loPpxq#bw_#v|{CbtY~jGqeMb{iF|n\\~mbDzeVh_Wr|Efc\\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg#|kHntyArpb#bijCk_Kv~eGyqTj_|#`uV`k|DcsNdwxAott#r}q#_gc#nu`CnvHx`k#dse#j|p#zpiAp|gEicy#`omFvaErfo#igQxnlApqGze~AsyRzrjAb__#ftyB}pIlo_BflmA~yQftNboWzoAlzp#mz`#|}_#fda#jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC",
"levels": "BBBAAAAABAABAAAAAABBAAABBAAAABBAAABABAAABABBAABAABAAAABABABABBABAABB"
},
"warnings": [ ],
"waypoint_order": [ 0, 1 ]
} ]
}
Let's say you used the standard http client libraries and now have the response in a String.
JSONObject jsonObject = new JSONObject(response); // parse response into json object
JSONObject routeObject = jsonObject.getJSONObject("route"); // pull out the "route" object
JSONObject durationObject = jsonObject.getJSONObject("duration"); // pull out the "duration" object
String duration = durationObject.getString("text"); //this should be the duration text value (20 hours 40 mins)
You will have to wrap all that in a try-catch block to catch the JSONExceptions.

Related

Exception in thread "AWT-EventQueue-0" javax.json.stream.JsonParsingException: Unexpected char 100 at (line no=1, column no=2, offset=1

I have a json file which I got from my backend.
The json file is as follows.
{
"documentTemplate": {
"pageFormat": {
"pageWidth": "50",
"pageLength": "13",
"usePageLengthFromPrinter": false
},
"template": {
"header": [
" Delivery Order ",
"Date : ${date} NO. : ${no_surat} ",
"Customer: ${customer} Delivery Date: ${delivery_date}"
],
"detail": [
{
"table": "table_details",
"border": "true",
"columns": [
{
"source": "description",
"width": 9,
"caption": "DESCRIPTION"
},
{
"source": "do_hanwa_and_date",
"width": 9,
"caption": "DO HW / DATE HW"
},
{
"source": "qty",
"width": 9,
"caption": "QTY"
},
{
"source": "nett",
"width": 9,
"caption": "NETT"
},
{
"source": "gross",
"width": 9,
"caption": "GROSS"
},
{
"source": "size",
"width": 9,
"caption": "SIZE"
},
{
"source": "location",
"width": 9,
"caption": "LOCATION"
},
{
"source": "urut",
"width": 9,
"caption": "URUT"
}
]
},
" ",
" ",
" ___________ ___________ ",
" (Signature) (Signature) "
]
}
},
"documentValue": {
"date": "13-05-2019",
"no_surat": "01024/05/DO-MARU/19JKT",
"customer": "PT. WIJAYA STEELINDO",
"delivery_date": "13-05-2019",
"table_details": [
{
"description": "03NKBTL190205005/12",
"do_hanwa_and_date": "46916 / 29-03-2019",
"qty": "1",
"nett": "4,568",
"gross": "4,616",
"size": "0.70MM X 151.8MM",
"location": "PT2212",
"urut": 64592
},
{
"description": "03NKBTL190204997/04",
"do_hanwa_and_date": "46916 / 29-03-2019",
"qty": "1",
"nett": "4,504",
"gross": "4,552",
"size": "0.70MM X 151.8MM",
"location": "PU5111",
"urut": 64591
}
]
}
}
To process the data: I use Gson.
public class Report {
String filePathString;
public HashMap<String, String> convertJsonToObject() {
Gson gson = new Gson();
try (JsonReader reader = new JsonReader(new FileReader(this.filePathString) )) {
// Converting JSON File to Java Object
HashMap<String, String> hashMapResult = gson.fromJson(reader, HashMap.class);
return hashMapResult;
} catch (IOException e) {
}
return null;
}
It's time to use the data from the GSON converter.
I use JSwing.
private void jButtonCompileGsonActionPerformed(java.awt.event.ActionEvent evt) {
// Create a report, param => file`s path
Report report = new Report(jTextFieldPathFile.getText());
// Read the file, as the return is a hashMap
HashMap<String, String> result = report.convertJsonToObject();
// Get based key
String documentTemplate = String.valueOf(result.get("documentTemplate")).replaceAll("\r?\n", "");
String documentValue = String.valueOf(result.get("documentValue")).replaceAll("\r?\n", "");
// Just to clarify
System.out.println(documentTemplate);
System.out.println(documentValue);
}
The result is:
documentTemplate => {pageFormat={pageWidth=50, pageLength=13, usePageLengthFromPrinter=false}, template={header=[ Delivery Order , Date : ${date} NO. : ${no_surat} , Customer: ${customer} Delivery Date: ${delivery_date}], detail=[{table=table_details, border=true, columns=[{source=description, width=9.0, caption=DESCRIPTION}, {source=do_hanwa_and_date, width=9.0, caption=DO HW / DATE HW}, {source=qty, width=9.0, caption=QTY}, {source=nett, width=9.0, caption=NETT}, {source=gross, width=9.0, caption=GROSS}, {source=size, width=9.0, caption=SIZE}, {source=location, width=9.0, caption=LOCATION}, {source=urut, width=9.0, caption=URUT}]}, , , ___________ ___________ , (Signature) (Signature) ]}}
documentValue => {date=13-05-2019, no_surat=01024/05/DO-MARU/19JKT, customer=PT. WIJAYA STEELINDO, delivery_date=13-05-2019, table_details=[{description=03NKBTL190205005/12, do_hanwa_and_date=46916 / 29-03-2019, qty=1, nett=4,568, gross=4,616, size=0.70MM X 151.8MM, location=PT2212, urut=64592.0}, {description=03NKBTL190204997/04, do_hanwa_and_date=46916 / 29-03-2019, qty=1, nett=4,504, gross=4,552, size=0.70MM X 151.8MM, location=PU5111, urut=64591.0}]}
I use this library: SimpleESCP
From these libraries, the interpretation is as follows.
import javax.json.JsonObject;
public class JsonDataSource implements DataSource {
private static final Logger LOG;
private JsonObject source;
public JsonDataSource(String jsonString){
}
}
I use it like this and get the following error message:
JsonDataSource jsonDataSource = new JsonDataSource(documentValue);
Exception in thread "AWT-EventQueue-0" javax.json.stream.JsonParsingException: Unexpected char 100 at (line no=1, column no=2, offset=1)
Please help and advice.
Thank you.

Incorrect JSON format sent from an app

How can I send JSONArray from Android client to server?
getJsonArray() is a function which return an JsonArray but when I send array to server it looks like this:
{
"IMEI": "xxxxxxxxxxxxxxx",
"Puls": ["101", "125", "103", "81"],
"Pasi": ["0", "0", "0", "0"],
"Latitudine": ["0", "0", "0", "0"],
"Longitudine": ["0IMEI=xxxxxxxxxxxxxxx", "0IMEI=xxxxxxxxxxxxxxx", "0IMEI=xxxxxxxxxxxxxxx", "0"]
}
I don't know why first IMEI is on right place and the others is not...
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
for (int i = 0; i < getJsonArray().length(); i++) {
writer.write(getPostDataString(getJsonArray().getJSONObject(i)));
}
The array inside the main array should look like this for example :-
"Puls": [
{
"number" : "101"
},
{
"number" : "125"
},
{
"number" : "103"
},
{
"number" : "81"
},
]
Try to format the arrays like this...
String strloadMainCategory = "api"+URLEncoder.encode("","UTF-8");
RestClient restClient = new RestClient(strloadMainCategory);
try {enter code here
restClient.Execute(RequestMethod.GET);
} catch (Exception e) {}

Formatting Json Code in Java

I need to convert the following Json code into Java.
{
"service": {
"type": "nyd",
"discount": 0.20,
"items": [
{
"asin": "....",
"link": "http://amazon.com/.....",
"quantity": 2
},
// ...
],
// See /addresses
"shipping_address": {
"full_name": "Mr Smith",
"street1": "Some Mission St",
"street2": "", // Optional
"city": "San Francisco",
"state": "CA",
"zip": "94000",
"country": "US",
"phone": "1234567890"
}
}
}
I'm currently implementing this by using the following code:
String postUrl = "https://API.example.com";
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPostRequest = new HttpPost(postUrl);
StringEntity postingString = new StringEntity("{\"service\" : {\"type\":\"nnn\", \"discount\":" + 0.2 + ",\"items\" : [ { \"asin\":\"B018Y1XXT6\", \"link\":\"https://www.amazon.com/Yubico-Y-159-YubiKey-4-Nano/dp/B018Y1XXT6/\", \"quantity\":" + 1 + " } ], \"shipping_address\" : {\"full_name\":\"Steven Smith\", \"street1\":\"11 Man Rd\", \"street2\":\"\", \"city\":\"Woonsocket\", \"state\":\"RI\", \"zip\":\"02844\", \"country\":\"US\", \"phone\":\"7746536483\" } } } ");
Mote: the values are different but I'm trying to achieve the same syntax.
System.out.println("Post String value: " + IOUtils.toString(postingString.getContent()));
httpPostRequest.addHeader("Authorization", "Token " + apiKey);
httpPostRequest.setEntity(postingString);
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.addHeader("content-type", "application/x-www-form-urlencoded");
HttpResponse response = httpClient.execute(httpPostRequest);
System.out.println(response.toString());
The "postString" value is:
{"service" : {"type":"nnn", "discount":0.2,"items" : [ { "asin":"B018Y1XXT6", "link":"https://www.amazon.com/Yubico-Y-159-YubiKey-4-Nano/dp/B018Y1XXT6/", "quantity":1 } ], "shipping_address" : {"full_name":"Steven Smith", "street1":"11 Man Rd", "street2":"", "city":"Woonsocket", "state":"RI", "zip":"02844", "country":"US", "phone":"17746536483" } } }
However, when I attempt to submit the request I get a Bad Request error.
How can I format the String correctly?
Thanks
You have sent an incorrect json String if you want to go with the json provided .Following are the errors:
1) "service = {\"type\" should be {\"service\" : {\"type
2) discount should not be a string
\"discount\":\"0.2\", should be \"discount\":" + 0.2 + ",
3) items = [ should be \"items\" : [
4) quantity should not be string
\"quantity\":\"1\" } should be \"quantity\":" + 1 + "}
5) comma missing before shipping address key
] shipping_address = should be ], \"shipping_address\" :
6) add one more } at the end

Delete a child attribute from json file

I have the following HTTP JSON-response in Java, which represents a user object.
{
"account": "Kpatrick",
"firstname": "Patrick",
[
],
"instances":
[
{
"id": "packerer-pool",
"key": "packerer-pool123",
"userAccount": "kpatrick",
"firstname": "Patrick",
"lastname": "Schmidt",
}
],
"projects":
[
{
"id": "packerer-projectPool",
"projectKey": "projectPool-Pool",
"cqprojectName": "xxxxx",
},
{
"id": "packerer-secondproject",
"projectKey": "projectPool-Pool2",
"cqprojectName": "xxxx",
},
{
"id": "packerer-thirdproject",
"projectKey": "projectPool-Pool3",
"cqprojectName": "xxxx",
}
],
"clients":
[
],
"dbid": 76864576,
"version": 1,
"id": "dbpack21"
}
Now, I want to search a specific project with the help of the projectkey (for example "projectPool-Pool2"). After that, I want to delete the element completely. Because my target is to send a HTTP post-call without this project.
The result should be similar to below for my HTTP post-call:
{
"account": "Kpatrick",
"firstname": "Patrick",
[
],
"instances":
[
{
"id": "packerer-pool",
"key": "packerer-pool123",
"userAccount": "kpatrick",
"firstname": "Patrick",
"lastname": "Schmidt",
}
],
"projects":
[
{
"id": "packerer-projectPool",
"projectKey": "projectPool-Pool",
"cqprojectName": "xxxxx",
},
{
"id": "packerer-thirdproject",
"projectKey": "projectPool-Pool3",
"cqprojectName": "xxxx",
}
],
"clients":
[
],
"dbid": 76864576,
"version": 1,
"id": "dbpack21"
}
First i have parsed the response to a string.
private static String getContent(HttpResponse response) {
HttpEntity entity = response.getEntity();
if (entity == null) return null;
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = reader.readLine();
reader.close();
return line;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
And now i am trying to search the specific project, but i don't know how to continue.
String StringResponse = getContent(JsonResponse);
JSONObject jsonObject = new JSONObject(StringResponse);
JSONArray ProjectsArray= jsonObject.getJSONArray("projects");
Is that approach correct?
Best Regards!
Once you have your array, try something like...
// Array to store the indexes of the JSONArray to remove
ArrayList<Integer> indexesToRemove = new ArrayList<Integer>();
// Iterate through projects array, check the object at each position
// if it contains the string you want, add its index to the removal list
for (int i = 0; i < projectsArray.length; i++) {
JSONObject current = projectsArray.get(i);
if (current.get("projectKey") == "**DESIRED PROJECT KEY**") {
indexesToRemove.add(i);
}
}
Now you can iterate through your indexes to remove, and remove the corresponding object from the array with the JSONArrays remove method (not sure what it is called, the code above is from memory). Make sure to remove your items BACKWARDS, otherwise you will delete earlier items, which will change the indexes, resulting in your removing an incorrect item if you then remove another index.
// Going through the list backwards so we can remove the highest item each
//time without affecting the lower items
for (int i = indexesToRemove.size()-1; i>=0; i--) {
projectsArray.remove(indexesToRemove.get(i));
}

Cannot parse JSONArray using GSON

I have encountered a problem whilst developing my Android application. My problem is that I don't know how to parse JSON code from an URL using GSON. I searched Google and SO for about an hour or so, but nothing worked for me. Everything I found on the internet referred to custom JSON code, not code from an URL. Here is a small sample of the data I have.
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"price": "3.65",
"address": "3885, Boulevard Saint-Rose",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
"price": "3.67",
"address": "3885, Saint-Mary",
"diesel": "0",
"id": "33872",
"lat": "45.492907",
"lng": "-73.740715",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "2.0km"
}
]
}
I am a beginner at JSON/GSON so I need a bit of help. Here is what I have:
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json?callback=?";
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
longitude = rootobj.get("price").getAsString();
latitude = rootobj.get("address").getAsString();
} catch (Exception e) {
e.printStackTrace();
}
I tried a loop to parse the array but that failed miserably. Any help regarding this problem is highly appreciated.
------------------------------EDIT-----------------------------------------------
I am extremely sorry about the incorrrect JSON code. I have updated the code but still cannot figure out the solution.
You JSON is wrong:
"date": "3 hours agp",
"distance": "1.9km"
}
{
"country": "Canada",
To coorect it, you must add a ,
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
Try this, using the basic org.json.JSONObject and org.json.JSONArray it works fine for me...
// This string is the JSON you gave as imput
String json = "{ \"status\": { \"error\": \"NO\", \"code\": 200, \"description\": \"none\", \"message\": \"Request ok\" }, \"geoLocation\": { \"city_id\": \"147\", \"city_long\": \"Saint-Laurent\", \"region_short\": \"QC\", \"region_long\": \"Quebec\", \"country_long\": \"Canada\", \"country_id\": \"43\", \"region_id\": \"35\" }, \"stations\": [ {\"country\": \"Canada\",\"price\": \"3.65\",\"address\": \"3885, Boulevard Saint-Rose\",\"diesel\": \"0\",\"id\": \"33862\",\"lat\": \"45.492367\",\"lng\": \"-73.710915\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"1.9km\" }, {\"country\": \"Canada\",\"price\": \"3.67\",\"address\": \"3885, Saint-Mary\",\"diesel\": \"0\",\"id\": \"33872\",\"lat\": \"45.492907\",\"lng\": \"-73.740715\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"2.0km\" } ]}";
try{
JSONObject rootobj = new JSONObject(json);
JSONArray array = rootobj.getJSONArray("stations");
for( int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
String price = o.getString("price");
String address = o.getString("address");
//...
}
}catch(JSONException jse){
// Manage Exception here
}
Try below code to fetch data from url and parse the response using Gson.
Note : Remove "?callback=?" from your url, that will remove "?(" from your response
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json";
URL u = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) u.openConnection();
request.setRequestMethod("GET");
request.connect();
int status = request.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
JsonElement element = new Gson().fromJson (br, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
JsonArray jArray = jsonObj.get("stations").getAsJsonArray();
for (int i = 0, size = jArray.length(); i < size; i++) {
JSONObject jObj = jArray.getJSONObject(i);
System.out.println(" Price : " + jObj.get("price").toString());
System.out.println(" Address : " + jObj.get("address").toString());
}
}
} catch (MalformedURLException ex) {
// Manage Exception here
} catch (IOException ex) {
// Manage Exception here
}

Categories

Resources