简体   繁体   English

是否有一种从JSON文件获取结果的方法?

[英]Is there a method for getting the results from the JSON-file?

In the following code the "results", "geometry", "location", "lat" and "lng" are hardcoded. 在以下代码中,“结果”,“几何形状”,“位置”,“纬度”和“ lng”被硬编码。

The problem is, if Google changes some of those words my code won't work anymore. 问题是,如果Google更改了某些单词,我的代码将无法再使用。 So my question is: is there a method in the Google maps API or the JSON library which solves my problem? 所以我的问题是:Google Maps 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.");
        }

    }

You can use Google client lib . 您可以使用Google客户端lib Then you might get the coordinates like this. 然后,您可能会得到这样的坐标。

    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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM