Google 在 Android 中通过 HTTPS 映射反向地理编码

Google maps reverse geocoding via HTTPS in Android

我正在制作 google 地图应用。由于 Geocoder class returns 为空(在 [0] 处超出范围),我目前正在尝试 HTTPS Google 映射反向地理编码。 这是我的 onClick 调用:

  public JSONArray getAddress(LatLng latLng) throws IOException {
    URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?latlng="+latLng.latitude+","+latLng.longitude+"&key=AIza***********************");
    Async async =new Async();
    async.execute(url);
    JSONArray response = async.jsonArray;

    return response;
}

这是异步子class:

public class Async extends AsyncTask<URL, Void, JSONArray> {
    public JSONArray jsonArray;
    @Override
    protected JSONArray doInBackground(URL... params) {
        BufferedReader reader;
        InputStream is;

        try {

            StringBuilder responseBuilder = new StringBuilder();
            HttpURLConnection conn = (HttpURLConnection) params[0].openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is));
            for (String line; (line = reader.readLine()) != null; ) {
                responseBuilder.append(line).append("\n");
            }
            jsonArray = new JSONArray(responseBuilder.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonArray;
    }

和manifest.xml:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

点击方法:

@Override
public void onMapClick(LatLng latLng) {
    JSONArray js=null;
    try {
         js = getAddress(latLng);
         mMap.addMarker(new MarkerOptions().position(latLng).title(js.getString(0)).draggable(true));//NullPointer
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException p) {
        //todo

    }

4 天以来,我一直在尝试获得与 NullPointerException 不同的东西。知道我做错了什么吗?在以调试模式连接的平板电脑上测试。 任何帮助都会有用。我很绝望。

由于 AsyncTask 是 Activity 的子类,您只需将 LatLng 分配给 Activity 的成员变量,以便在 AsyncTask 中访问它。

然后,在onPostExecute()中添加Marker。

首先,对 Activity 代码的更改。 除了 JSONArray:

之外,创建一个 LatLng 成员变量
public class MyMapActivity extends AppCompatActivity implements OnMapReadyCallback
{

    JSONArray js;
    LatLng currLatLng;
    //...............

然后,修改onMapClick,将LatLng赋给实例变量:

@Override
public void onMapClick(LatLng latLng) {
    JSONArray js=null;
    try {

         //assign to member variable:
         currLatLng = latLng;

         //don't use the return value:
         getAddress(latLng);

         //remove this:
         //mMap.addMarker(new MarkerOptions().position(latLng).title(js.getString(0)).draggable(true));//NullPointer
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException p) {
        //todo

    }

然后,在收到响应后使用 onPostExecute 放置标记。 另一个主要问题是 JSON 响应是一个 JSON 对象,其中包含一个 JSON 数组。 固定在下面的代码中:

public class Async extends AsyncTask<URL, Void, JSONArray> {
    public JSONArray jsonArray;

    @Override
    protected JSONArray doInBackground(URL... params) {
        BufferedReader reader;
        InputStream is;
        try {

            StringBuilder responseBuilder = new StringBuilder();
            HttpURLConnection conn = (HttpURLConnection) params[0].openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is));
            for (String line; (line = reader.readLine()) != null; ) {
                responseBuilder.append(line).append("\n");
            }
            JSONObject jObj= new JSONObject(responseBuilder.toString());
            jsonArray = jObj.getJSONArray("results");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonArray;
    }


    @Override
    protected void onPostExecute(JSONArray jsonArrayResponse) {
        js = jsonArrayResponse;
        try {
            if (js != null) {
              JSONObject jsFirstAddress = js.getJSONObject(0);
              mMap.addMarker(new MarkerOptions().position(currLatLng).title(jsFirstAddress.getString("formatted_address")).draggable(true));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

请注意,您不需要 return 来自 getAddress() 的任何内容,因此只需将 return 类型设为 void 并让 AsyncTask 在执行后完成其余的工作:

  public void getAddress(LatLng latLng) throws IOException {
    URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?latlng="+latLng.latitude+","+latLng.longitude+"&key=AIza***********************");
    Async async =new Async();
    async.execute(url);
    //JSONArray response = async.jsonArray;
    //return response;
  }