【问题标题】:Google Map V2 geocoder returns nullGoogle Map V2 地理编码器返回 null
【发布时间】:2018-05-28 15:18:55
【问题描述】:

以下是我的谷歌地图 v2 地理编码代码。我从 longclick 监听器上的地图获取纬度和经度。我想解码这个纬度和经度以获得地址。但是我的地址大小总是返回零。怎么回事不知道。

 Log.i("lat long", ": "+arg0.latitude+","+arg0.longitude); 
 Log.i("Geocoder returns", ": "+geocoder.getFromLocation(arg0.latitude,arg0.longitude,1));
               addresses = geocoder.getFromLocation(arg0.latitude,arg0.longitude,1);
               Log.i("Print address array", ": "+addresses.size()+","+addresses); 

【问题讨论】:

    标签: android google-maps


    【解决方案1】:
     private String getAddress(Double lat, Double lng)
     {
    
        try 
        {
          Geocoder geocoder = new Geocoder(this, Locale.getDefault());
          List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
          StringBuilder sb = new StringBuilder();
          if (addresses.size() > 0) 
          {
            Address address = addresses.get(0);
    
            sb.append(address.getLocality()).append(", ");
            sb.append(address.getCountryName());
          }
    
         String addressString = sb.toString();
         return addressString;
        } 
        catch (IOException e) 
        {
            return "No Address Found";
        }
    
    }
    

    现在查看函数返回的地址。

    【讨论】:

      【解决方案2】:

      根据documentation

      如果未找到匹配项或没有可用的后端服务,则返回 null 或空列表。

      所以地理编码器可能无法确定给定坐标的地址。

      确保在清单中声明 INTERNET 权限。

      <uses-permission android:name="android.permission.INTERNET" />
      

      【讨论】:

      • 这是什么后端服务
      • 清单中使用了 Internet 权限。当长按地图时,我可以得到lat long,但是从lat long,地址没有得到。
      • 地理编码服务由谷歌提供,由Geocoder API内部调用
      • 请发布您没有收到任何结果的样本纬度、经度对
      • 经纬度:5.103488681754595,100.49531120806932
      【解决方案3】:

      这是我用的:

      package com.exercise.AndroidFromLocation;
      
      import java.io.IOException;
      import java.util.List;
      import java.util.Locale;
      
      import android.app.Activity;
      import android.location.Address;
      import android.location.Geocoder;
      import android.os.Bundle;
      import android.widget.TextView;
      
      public class AndroidFromLocation extends Activity {
      
      double LATITUDE = 37.42233;
      double LONGITUDE = -122.083;
      
         /** Called when the activity is first created. */
         @Override
         public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
             TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
             TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
             TextView myAddress = (TextView)findViewById(R.id.myaddress);
      
             myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
             myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
      
             Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
      
             try {
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
      
        if(addresses != null) {
         Address returnedAddress = addresses.get(0);
         StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
         for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
          strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
         }
         myAddress.setText(strReturnedAddress.toString());
        }
        else{
         myAddress.setText("No Address returned!");
        }
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        myAddress.setText("Canont get Address!");
       }
      
         }
      }
      

      【讨论】:

      【解决方案4】:

      android 地理编码器不稳定,大多数时候我也得到了 null。所以,我们改用Google Map API Web Service。这比 IMO 好得多。

      下面是我们使用的代码。基本上,只需使用 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);
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-14
        • 1970-01-01
        • 2016-03-23
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-17
        相关资源
        最近更新 更多