android地理编码器不稳定,大多数时候我也得到了null。因此,我们切换到使用Google Map API Web Service。国际海事组织要好得多。
下面是我们使用的代码。基本上,只需使用 httpClient 发送 GET 请求,响应为 JSON 格式。
public class GoogleGeocodingService implements GeocodingService {
private static final Logger LOGGER = LoggerFactory.getInstance().getLogger(GoogleGeocodingService.class);
private static final String DEFAULT_LANG = "en";
private HttpClient httpClient;
/**
* Get httpClient.
*
* @return the httpClient
*/
public HttpClient getHttpClient() {
return httpClient;
}
/**
* Set httpClient.
*
* @param httpClient
* the httpClient to set
*/
public void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public String getSimpleReverseLocation(double latitude, double longitude) throws Exception {
return getSimpleReverseLocation(latitude, longitude, DEFAULT_LANG);
}
@Override
public String getSimpleReverseLocation(double latitude, double longitude, String language) throws Exception {
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
addParameter(params, "latlng", Double.toString(latitude) + "," + Double.toString(longitude));
addParameter(params, "language", language);
addParameter(params, "sensor", "true");
String response = getContent("http://maps.googleapis.com/maps/api/geocode/json", params);
try {
GeocodingResponse r = handleResponse(response, GeocodingResponse.class);
return r.getShortFormattedAddress();
} catch (Exception e) {
LOGGER.error(e.toString());
return "";
}
}
private static void addParameter(List<BasicNameValuePair> parameters, String key, String value) {
parameters.add(new BasicNameValuePair(key, value));
}
private String getContent(String url, List<BasicNameValuePair> parameters) throws Exception {
url = HttpClientUtils.createGetUrl(url, parameters);
//LOGGER.debug("URL: %s", url);
return HttpClientUtils.getContent(httpClient, new HttpGet(url), new InputStreamToStringConverter());
}
private <T> T handleResponse(String response, Class<T> clz) throws IOException {
//LOGGER.debug("Response: %s", response);
int first = StringUtils.indexOf(response, '{');
//LOGGER.debug("first position of '{' = %d", first);
if (first > 0) {
response = StringUtils.substring(response, first);
LOGGER.debug("Response: after clean server side error html from json response: %s", response);
}
return JacksonUtils.parse(response, clz);
}
}