Разбор транзита Json с гугл карт в андроид - PullRequest
0 голосов
/ 21 марта 2019

Мне нужно получить информацию о транзите с карт Google. Приведенный ниже код извлекает информацию из фиктивного файла JSON, однако, когда я указываю URL карт Google для извлечения информации JSON, я не получаю никакого результата. Ниже приведен мой код. Я новичок в этом, любые материалы, касающиеся этого, будут очень полезны.

{
   "geocoded_waypoints" : [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJN5C6QlXI5zsRdO3ozWMUp-c",
         "types" : [ "political", "sublocality", "sublocality_level_2" ]
      },
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJm-mTfEDJ5zsRNaF8cuQ7cR0",
         "types" : [ "route" ]
      }
   ],
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 19.081558,
               "lng" : 72.84999239999999
            },
            "southwest" : {
               "lat" : 19.053579,
               "lng" : 72.8306348
            }
         },
         "copyrights" : "Map data ©2019 Google",
         "legs" : [
            {
               "arrival_time" : {
                  "text" : "9:36pm",
                  "time_zone" : "Asia/Calcutta",
                  "value" : 1553184370
               },
               "departure_time" : {
                  "text" : "9:07pm",
                  "time_zone" : "Asia/Calcutta",
                  "value" : 1553182620
               },
               "distance" : {
                  "text" : "5.4 km",
                  "value" : 5415
               },
               "duration" : {
                  "text" : "29 mins",
                  "value" : 1750
               },
               "end_address" : "Hill Rd, Bandra West, Mumbai, Maharashtra 400050, India",
               "end_location" : {
                  "lat" : 19.0551507,
                  "lng" : 72.8306348
               },
               "start_address" : "Vakola, Santacruz East, Mumbai, Maharashtra, India",
               "start_location" : {
                  "lat" : 19.0789065,
                  "lng" : 72.84999239999999
               },
               "steps" : [
                  {
                     "distance" : {
                        "text" : "0.2 km",
                        "value" : 182
                     },
                     "duration" : {
                        "text" : "2 mins",
                        "value" : 126
                     },
                     "end_location" : {
                        "lat" : 19.0801031,
                        "lng" : 72.84953709999999
                     },
                     "html_instructions" : "Walk to Vakola Bridge",
                     "polyline" : {
                        "points" : "ejmsBmos{L?Ly@?w@?yBB?HA|@"
                     },
                     
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




public class ParseActivity extends AppCompatActivity {
    private TextView mTextViewResult;
    private RequestQueue mQueue;
    private LatLng origin = new LatLng(19.0803263, 72.84999239999999);
    private LatLng dest = new LatLng(19.0496701, 72.8306348);
    


    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parse);

        mTextViewResult = findViewById(R.id.text_view_result);
        Button buttonParse = findViewById(R.id.button_info);

        mQueue = Volley.newRequestQueue(this);

        buttonParse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 jsonParse();
            }
        });
    }

    private void jsonParse(){


        String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
       

        // Destination of route
        String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
       

        // Sensor enabled
        String sensor = "sensor=false";

        // Building the parameters to the web service
        String parameters = str_origin + "&" + str_dest + "&" + sensor;

        String mode = "transit";

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters +
                 "&key=" + "My-google-key" + "&mode=" + "transit";



        //Parsing the json shizz


//String url ="https://api.myjson.com/bins/kp9wz";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
            //@Override
                    public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONArray("steps"); //steps

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject steps = jsonArray.getJSONObject(i); //steps instead of employee

                        String distance = steps.getString("distance"); //distance instead of Firstname

                        String duration = steps.getString("duration");

                       String instructions = steps.getString("html_instructions");

                        mTextViewResult.append(distance + "," + duration + "," + instructions + "\n\n");

                        //int age = employee.getInt("age");
                        //String mail = employee.getString("mail");
                        //mTextViewResult.append(firstName + ", " + String.valueOf(age) + ", " + mail + "\n\n");


                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error){
                error.printStackTrace();
            }
        });

        mQueue.add(request);

    }

}

Мне нужна помощь в разборе этих деталей. Какие изменения я должен внести в мой код Java?

...