MapMyIndia Autosuggest API调用后ELocation的latitude与longitude返回null问题排查
解决MapMyIndia Autosuggest API返回经纬度为null的问题
首先得搞清楚为什么会出现这个情况:你拿到的ELocation类型是SUB_DISTRICT(亚区),这类行政区域属于范围性的地理实体,MapMyIndia的Autosuggest API默认不会返回它们的经纬度——毕竟一个区域没有唯一的精确坐标,只有中心点坐标需要额外请求才能获取。
下面给你几个可行的解决办法:
1. 修改Autosuggest请求,优先获取带经纬度的结果
如果你更需要POI(兴趣点)或具体地址这类自带经纬度的结果,可以在请求中添加类型过滤,让API只返回这类数据:
private void callAutoSuggestApi(String searchString) { MapmyIndiaAutoSuggest.builder() .query(searchString) .type("POI,ADDRESS") // 指定只返回POI和具体地址,这类结果通常带经纬度 .build() .enqueueCall(new Callback<AutoSuggestAtlasResponse>() { // 你的原有回调逻辑... }); }
另外,部分版本的MapMyIndia SDK支持直接在Autosuggest请求中开启经纬度返回,比如添加.includeLatLong(true)参数(如果你的SDK有这个方法的话),可以试试在builder里加上这个配置。
2. 对无经纬度的区域调用Geocode API补全坐标
如果你确实需要行政区域的中心点经纬度,可以在拿到ELocation后,调用MapMyIndia的Geocode API来获取该区域的坐标:
首先新增一个获取经纬度的方法:
private void fetchLocationCoordinates(String locationQuery) { MapmyIndiaGeocode.builder() .address(locationQuery) .build() .enqueueCall(new Callback<GeocodeResponse>() { @Override public void onResponse(@NonNull Call<GeocodeResponse> call, @NonNull Response<GeocodeResponse> response) { if (response.code() == 200 && response.body() != null) { ArrayList<GeocodeResult> geocodeResults = response.body().getResults(); if (!geocodeResults.isEmpty()) { GeocodeResult result = geocodeResults.get(0); double latitude = result.getLatitude(); double longitude = result.getLongitude(); // 在这里使用获取到的经纬度做后续处理 Log.e(TAG, "区域中心点坐标: " + latitude + ", " + longitude); } else { showToast("未找到该区域的坐标信息"); } } } @Override public void onFailure(@NonNull Call<GeocodeResponse> call, @NonNull Throwable t) { showToast("获取坐标失败: " + t.getMessage()); } }); }
然后在你的selectedPlace方法中判断并调用:
private void selectedPlace(ELocation eLocation) { Log.e(TAG, "onResponse: " + eLocation.toString()); recyclerView.setVisibility(View.GONE); // 检查经纬度是否为空 if (eLocation.getLatitude() == null || eLocation.getLongitude() == null) { // 拼接区域名称和地址作为Geocode的查询参数 String query = eLocation.getPlaceName() + ", " + eLocation.getPlaceAddress(); fetchLocationCoordinates(query); } else { // 经纬度存在,直接使用 double lat = Double.parseDouble(eLocation.getLatitude()); double lng = Double.parseDouble(eLocation.getLongitude()); // 你的后续业务逻辑... } }
3. 检查SDK版本和权限
确保你使用的是最新版的MapMyIndia SDK,旧版本可能存在某些参数支持不全的问题。另外,确认你的API密钥拥有访问Autosuggest和Geocode API的权限,权限不足也可能导致部分字段返回null。
内容的提问来源于stack exchange,提问作者Mohanasundar




