JSON 通过坐标获取地址

JSON get address by coordinates

我为 Android 创建了一个应用程序,它保存 GPS 坐标并显示地址。

我有一个功能:

public String getAddressByGpsCoordinates(String latlan) {

    requestQueue = Volley.newRequestQueue(this);

    String url=  "http://maps.googleapis.com/maps/api/geocode/json?latlng="+latlan+"&sensor=true&key=(I have a correct key :))";
    JsonObjectRequest request = new JsonObjectRequest(url,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

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

    requestQueue.add(request);
    return address;
}

一直返回NULL。 你能帮我看看我的代码有什么问题吗?

JsonObjectRequestRequestQueue 结合使用是一种异步机制——工作在后台执行,只要响应准备就绪,就会调用 onResponse 回调。

因此,您很可能在调用 onResponse 之前从您的方法中 return,并且由于未事先设置 address(您已展示, 无论如何), 它的值将是 null.

如果你想阻塞线程直到请求完成并设置 address 的值,你应该使用 RequestFuture: Can I do a synchronous request with volley?