简体   繁体   中英

Getting Driving Directions and retrieving the JSON object using Google Maps API V2

I am trying to retrieve the JSON object and parse through it so I can get the respective LatLng objects between 2 points on a map. So far I have implemented a test class that looks something like this:

/**
 * Necessary imports
 */

public class DemoDirections extends AsyncTask<String, Void, Void > {
    ArrayList<LatLng> latLngs;
    JsonFactory JSON_FACTORY = new JsonFactory();
    JsonParser jParser;

    public DemoDirections() {
        //To access the Maps and Directions API for directions
    }

    protected Void doInBackground(String... src) {

        String urlString = "http://maps.googleapis.com/maps/api/directions/json?" +
                "origin=" + src[0] +"&destination="+ src[1] +"&sensor=false";
        Log.d("URL", urlString);
        HttpURLConnection urlConnection = null;
        URL url = null;

        try {

            url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.connect();
            jParser = JSON_FACTORY.createJsonParser(urlConnection.getInputStream());
            String test = jParser.nextTextValue() != null ?  jParser.nextTextValue() : "its still null" ;
            Log.d("test string: ", test);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String... src)
    {

    }
}

I just wanted to print out the JSON as a string just to make sure that I have received the information correctly before I start parsing through the JSON input, but the call for jParser.nextTextValue() or jParser.textValue() always returns null, which leads me to think that I am not establishing to the Google API services correctly. I just want to see what I am missing to retrieve the JSON input and parse through it so I can get the LatLng objects setup.

Seems like your url is not providing an api key. A sample API require URL should be like this: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY

Sample working code:

String API_KEY = "YOUR_API_KEY_STRING";
String input = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";

private static boolean getAddressResult(String input, StringBuilder jsonResults) {
    try {

        URL requestUrl = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + input " + &key=" + API_KEY;
            );
        HttpURLConnection connection = (HttpURLConnection)requestUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();


        responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {

            BufferedReader reader = null;

            InputStream inputStream = connection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return false;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                long elapsedTime = System.currentTimeMillis();
                if(elapsedTime-currentTime>=5000) {
                   return false;
                }
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                return false;
            }

            Log.d("Test", buffer.toString());
            return buffer.toString();
        }
        else {
            Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
            return false
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        return false;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        return false;
    } catch (Expcetion e) {
        return false;
    }
    return false;
}

And please make sure you have to correct permissions (such as INTERNET) set up in your manifest file. You can also make sure that internet on your device is actually connected.

Have you tried to print out the data from 'urlConnection.getInputStream()'? The response data from ' http://maps.googleapis.com/maps/api/directions/json ?' should be a text string (Json format string) that you can read it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM