简体   繁体   中英

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.

The problem is, if Google changes some of those words my code won't work anymore. So my question is: is there a method in the Google maps API or the JSON library which solves my problem?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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