0

I am trying to get coordinates from a location entered from the user using HTTP request to Geocode API.

The address string I pass into the method is formatted with "%" in between the spaces so that it can be put into a URL.

Sometimes, it will return a null value and I have no idea why.

It works sometimes so I think there isn't a problem with the JSON array get lines.

public CheckLocation(String address) {
    try {
        String key = "insert key";
        String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "?key=" + key;

        // String key = "test/";

        URL urlObj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        // add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // Read JSON response and print
        JSONObject myResponse = new JSONObject(response.toString()); 

        double laditude = ((JSONArray)myResponse.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");
        double longitude = ((JSONArray)myResponse.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");
        formattedAddress = ((JSONArray)myResponse.get("results")).getJSONObject(0)
                .getString("formatted_address");
        coordinates = (laditude + "," + longitude);

    } 
    catch (Exception e) {
    e.printStackTrace();
    }
}   
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
ricemvm
  • 7
  • 2

1 Answers1

0

What about encoding parameters values? encode both address and key:

String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + 
URLEncoder.encode(address, "UTF-8"); + "?key=" + URLEncoder.encode(key, "UTF-8");

URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value

Ori Marko
  • 56,308
  • 23
  • 131
  • 233