Geocoder.getFromLocationName不适用于某些地方

时间:2018-04-09 09:34:43

标签: android google-maps

我正在尝试从正在搜索的字符串中获取位置。但是,在某些情况下,addressList返回大小为0(即H.M.教育中心,kolkata)。我没有经纬度来搜索这个地方。需要帮助。

String addressString = (String) adapterView.getItemAtPosition(position);
String addressString1 = (String) adapterView.getItemAtPosition(position);
List<Address> addressList = null;
Address address = null;
if (!TextUtils.isEmpty(addressString))
{
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try
    {
        addressList = geocoder.getFromLocationName(addressString, 1);
    }
    catch (IOException e)
    {
        e.printStackTrace();
        addressString = addressString1;
    }
    //noinspection ConstantConditions
    if(addressList != null && addressList.size() > 0)
    {
         address = addressList.get(0);
    }
}

1 个答案:

答案 0 :(得分:1)

作为替代方案,您可以使用Geocoding API或Places API网络服务。我检查了你的地址'H.M.教育中心,kolkata'在Geocoding API Web服务请求中找出了可以找到的坐标。使用以下地址查看Geocoder工具:

https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3DH.M.%2520education%2520centre%252C%2520kolkata

在您的Java代码中,我建议使用Github托管的Google Maps for Java Maps Services:

https://github.com/googlemaps/google-maps-services-java

使用此客户端库执行Web服务请求的代码段如下

GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("AIza...")
    .build();
GeocodingResult[] results =  GeocodingApi.geocode(context,
"H.M. education centre, kolkata").await();

可以在

找到当前版本库的Javadoc

https://googlemaps.github.io/google-maps-services-java/v0.2.7/javadoc/

另请注意,可以通过Places API网络服务找到此类地点。在这种情况下,代码段将是

GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("AIza...")
    .build();
TextSearchRequest req = PlacesApi.textSearchQuery(context, "H.M. education centre, kolkata");
try {
    PlacesSearchResponse resp = req.await();
    if (resp.results != null && resp.results.length > 0) {
        //Process your results here
    }
} catch(Exception e) {
    Log.e(TAG, "Error getting places", e);
}

我希望这有帮助!

相关问题