【问题标题】:Is there a method for getting the results from the JSON-file?有没有从 JSON 文件中获取结果的方法?
【发布时间】:2015-08-13 16:28:39
【问题描述】:

在以下代码中,“results”、“geometry”、“location”、“lat”和“lng”是硬编码的。

问题是,如果 Google 更改了其中一些字词,我的代码将不再工作。所以我的问题是:Google 地图 API 或 JSON 库中是否有解决我问题的方法?

private Location getCoordinates(Location l, JSONObject json) {
        try {
            JSONArray jsonObject1 = (JSONArray) json.get("results");
            JSONObject jsonObject2 = (JSONObject)jsonObject1.get(0);
            JSONObject jsonObject3 = (JSONObject)jsonObject2.get("geometry");
            JSONObject location = (JSONObject) jsonObject3.get("location");

             l.setLat(Double.parseDouble(location.get("lat").toString()));
             l.setLon(Double.parseDouble(location.get("lng").toString()));

             return l;
        } catch (Exception e) {
            throw new IllegalArgumentException("Country or zip not found.");
        }

    }

【问题讨论】:

  • 我怀疑他们会改变这些措辞。我的意思是,我看不出他们为什么会这样做
  • 我也对此表示怀疑,但这会很好,因为当他们更改它时,我不必更改代码。

标签: java json google-maps


【解决方案1】:

您可以使用Google client lib。然后你可能会得到这样的坐标。

    GeoApiContext context = new GeoApiContext().setApiKey("API_KEY");
    GeocodingResult[] results =  GeocodingApi.geocode(context,
            "1600 Amphitheatre Parkway Mountain View, CA 94043").await();
    for (GeocodingResult result : results) {
        System.out.println("LAT: " + result.geometry.location.lat);
        System.out.println("LNG: " + result.geometry.location.lng);
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多