geocoder.getFromLocationName returns only null

前端 未结 4 1471
长发绾君心
长发绾君心 2020-12-01 20:01

I am going out of my mind for the last two days with an IllegalArgumentException error I receive in Android code when trying to get a coordinates out of an addr

4条回答
  •  长情又很酷
    2020-12-01 20:11

    Had the same problem. Pooling didn't work so I used this to get the location: Geocoding Responses

    Use this class to get JSONObject of location:

    public class GetLocationDownloadTask extends AsyncTask {
    
        @Override
        protected String doInBackground(String... strings) {
    
    
            String result = "";
            URL url;
            HttpURLConnection urlConnection;
            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream is = urlConnection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(is);
    
                int data = inputStreamReader.read();
                while(data != -1){
                    char curr = (char) data;
                    result += curr;
                    data = inputStreamReader.read();
                }
                return result;
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
    
            if(result != null) {
                try {
                    JSONObject locationObject = new JSONObject(result);
                    JSONObject locationGeo = locationObject.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
    
    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
    
        }
    

    You can create and run the class instance like this:

    String link = "https://maps.googleapis.com/maps/api/geocode/json?address=" + addressString + "&key={YOUR_API_KEY}";
    
    GetLocationDownloadTask getLocation = new GetLocationDownloadTask();
    
    getLocation.execute(link);
    

提交回复
热议问题