Google GeoCoding返回ZERO_RESULTS

时间:2012-09-23 12:39:54

标签: java google-maps-api-3 geocoding reverse-geocoding

我正在使用谷歌地理编码API来获得结果,但它返回“ZERO_RESULTS”。以下是代码

public class GeoCode {

public static void main(String[] args) throws Exception {
    GeoCode.geocode("latlng=40.714224,-73.961452");
    }
private static final String URL = "http://maps.googleapis.com/maps/api/geocode/json";


public static void geocode(String address) throws Exception {

    URL url = new URL(URL + "?" + URLEncoder.encode(address, "UTF-8") + "&sensor=false");
    URLConnection conn = url.openConnection();
    ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
    IOUtils.copy(conn.getInputStream(), output);
    output.close();

    //JSONObject json = new JSONObject(output.toString());
    System.out.println(output.toString());
}
}

当我在浏览器的地址栏上手动使用地址时,它会在浏览器上显示json结果。但是上面的代码实际上有什么问题,它在json中返回“ZERO_RESULTS”?

1 个答案:

答案 0 :(得分:2)

您不需要使用URLEncoder对地址进行编码,只需执行:

URL url = new URL(URL + "?" + address + "&sensor=false");
URLConnection conn = url.openConnection();
ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
IOUtils.copy(conn.getInputStream(), output);
output.close();
System.out.println(output.toString());

或者更好:

   URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?" + address + "&sensor=false");
try {
    output = new Scanner(url.openStream()).useDelimiter("\\A").next());
} catch (java.util.NoSuchElementException e) {
    //empty result
}