使用 Java 在 Android Studio 中从 Google 地理编码 API 获取经度和纬度值

Get Longitude and Latitude values from Google Geocoding API in Android Studio with Java

这是我的 getCurrentLocation 方法:

private CurrentLocation getCurrentLocation(String jsonData) throws JSONException {
    JSONObject object = new JSONObject(jsonData);
    JSONArray results = object.getJSONArray("results");

    JSONObject objects = results.getJSONObject(0);
    JSONObject geometry = objects.getJSONObject("geometry");
    JSONObject location = geometry.getJSONObject("location");
    //instance of CurrentLocation class
    CurrentLocation currentLocation = new CurrentLocation();
    currentLocation.setLongitude(location.getDouble("lat"));
    currentLocation.setLatitude(location.getDouble("lng")); 
    Log.i(TAG, "FROM JSON: " + currentLocation.getLatitude());
    Log.i(TAG, "FROM JSON: " + currentLocation.getLongitude());
return currentLocation;
}

打印出 FROM JSON: -117.9145036 FROM JSON: 33.8352932 是正确的,

我在行中收到 NullPointerException 错误:

 private void updateLocation() {
       getForecast(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude());
}

我知道 private void getForecast(double latitude, double longitude) 有效,因为我输入了两个双精度数作为参数并且它有效。 我对 android 还是很陌生,我知道工作室本身有一个地理定位器,但我想从 API 开始。我不确定 nullException 指向什么,我们将不胜感激。谢谢。

以下是我的其他方法,如果有帮助的话: 创建时:

This is my Oncreate method:

public void onClick(View view) {
             String name = mNameField.getText().toString();
             getLocation(name);
             updateLocation(); // error here?

和获取位置:

public void getLocation(String name) {
    //get Google api
    String geoLocatingUrl = "https://maps.googleapis.com/maps/api/geocode/json?address="+name+"&key=AIzaSyAsJJIEeB952KpjpoFoMuYHd6gev85uzYs";

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(geoLocatingUrl)
                .build();

        Call call = client.newCall(request);
        //UI thread executes enqueue, sends to OKHttp Library gets data, response or failure back to UI
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

        @Override
        public void onResponse(Response response) throws IOException {

            try {
                   String jsonData = response.body().string();
                if (response.isSuccessful()) {

                    mCurrentLocation = getCurrentLocation(jsonData);
                    Log.v(TAG, jsonData);

                } else {
                    alertUserAboutError();

                }
            } catch (IOException e) {
                Log.e(TAG, "Exception caught: ", e);

            }
            catch (JSONException e) {
            }
        }
    });
}

和getForecast:

private void getForecast(double latitude, double longitude) {
    String apiKey = "//myapikey";

    String forecastUrl =  "https://api.forecast.io/forecast/" + apiKey +
            "/" + latitude + "," + longitude;

    if (isNetworkAvailable()) { //runs if network is there and available
        toggleRefresh();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(forecastUrl)
                .build();

        Call call = client.newCall(request);
        //UI thread executes enqueue, sends to OKHttp Library gets data, response or failure back to UI
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toggleRefresh();
                    }
                });
                alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toggleRefresh();
                    }
                });
                try {
                    String jsonData = response.body().string();
                    if (response.isSuccessful()) {

                        mCurrentWeather = getCurrentDetails(jsonData);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateDisplay();
                            }
                        });

                    } else {
                        alertUserAboutError();
                    }
                }
                catch (IOException e) {
                }
                catch (JSONException e) {
                }
            }
        });
    }
    else {
        Toast.makeText(this, getString(R.string.
                        network_unavailable_message),
                Toast.LENGTH_LONG
        ).show();
    }
}

我假设您正在尝试打印 class "CurrentLocation" 的对象。所以值为@42c49c78.What 你要做的就像

 Log.i(TAG, "FROM JSON: " + currentLocation.getLatitude());

希望对您有所帮助。