java - Google 地理编码返回 ZERO_RESULTS

标签 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”?

最佳答案

您不需要使用 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
}

关于java - Google 地理编码返回 ZERO_RESULTS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552425/

相关文章:

java - java中类层次结构中的类是如何初始化的?

javascript - 将谷歌地图点的坐标提取到 HTML 中的谷歌表格

geolocation - 如何从字符串中过滤非地址信息

java - 预期 HibernateException : Wrong column type:x,:Sybase 上的 y

Java 反射 : Get a Field's Value where the Field is of an Interface Type

Java readInt 方法返回 Scala 中 Int 的 LittleEndian 而不是 BigEndian 值

google-maps - 任何人都知道 gwt api 何时支持 google maps v3

javascript - Google map javascript api - map 未显示在打印或打印预览中,但形状显示

php - Laravel 5.5 地理编码器

javascript - Mapbox Geolocation,如何加载到 map 中?