使用getFromLocation将坐标转换为地址时的反向地理编码问题

问题描述:

使用getFromLocation反转地理编码时遇到问题。 我正在使用Android Studio并通过设备监视器传递坐标。使用getFromLocation将坐标转换为地址时的反向地理编码问题

坐标显示正常,但地址仍为空。

我已经尝试了一些在这里发布的*解决方案,即使已知没有崩溃,我仍然无法获得地址。

以下是代码片段。我在用。

@Override 
    public void onLocationChanged(Location location){ 
     double lat = (location.getLatitude()); 
     double lng = (location.getLongitude()); 
     latituteField.setText(String.valueOf(lat)); 
     longitudeField.setText(String.valueOf(lng)); 


    //Get address base on location 
    try{ 
     Geocoder geo = new Geocoder(this, Locale.getDefault()); 
     List<Address> addresses = geo.getFromLocation(lat, lng, 1); 
     if (addresses.isEmpty()) { 
      endereco.setText("Waiting for Location"); 
     } 
     else { 
      if (addresses.size() > 0) { 
       Log.d(TAG,addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName()); 

      } 
     } 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

在地理编码线,我已经尝试了这个藏汉

Geocoder geo = new Geocoder(GPSActivity.this.getApplicationContext(), Locale.getDefault()); 

,如果需要,这里是整个活动

import android.app.Activity; 
import android.content.Context; 
import android.location.Address; 
import android.location.Criteria; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 
import android.widget.Toast; 
import java.util.List; 
import java.util.Locale; 

/** 
* Created by Usuário on 05/02/2015. 
*/ 
public class GPSActivity extends Activity implements LocationListener { 
    private static final String TAG = null; 
    private TextView latituteField; 
    private TextView longitudeField; 
    private TextView endereco; 
    private LocationManager locationManager; 
    private String provider; 

    /** 
    * Called when the activity is first created. 
    */ 

    @Override 
    public void onCreate(Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.gps); 
     latituteField = (TextView) findViewById(R.id.TextView02); 
     longitudeField = (TextView) findViewById(R.id.TextView04); 
     endereco = (TextView) findViewById(R.id.Endereco); 

     //Get the Location Manager 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     //Define the criteria how to select location provider -> use 
     // default 

     Criteria criteria = new Criteria(); 
     provider = locationManager.getBestProvider(criteria,false); 
     Location location = locationManager.getLastKnownLocation(provider); 

     // Initialize the location fields 
     if (location != null){ 
      System.out.println("Provider " + provider + " has been selected"); 
      onLocationChanged(location); 
     }else{ 
      latituteField.setText("Locação não disponível"); 
      longitudeField.setText("Locação não disponível"); 
     } 
    } 

    /** 
    * Request updates at startup 
    */ 
    @Override 
    protected void onResume(){ 
     super.onResume(); 
     locationManager.requestLocationUpdates(provider, 400, 1, this); 
    } 

    /** 
    * Remove the LocationListener updates when Activity is paused 
    */ 
    @Override 
    protected void onPause(){ 
     super.onPause(); 
     locationManager.removeUpdates(this); 
    } 

    @Override 
    public void onLocationChanged(Location location){ 
     double lat = (location.getLatitude()); 
     double lng = (location.getLongitude()); 
     latituteField.setText(String.valueOf(lat)); 
     longitudeField.setText(String.valueOf(lng)); 


     //Get address base on location 
     try{ 
      Geocoder geo = new Geocoder(GPSActivity.this.getApplicationContext(), Locale.getDefault()); 
      List<Address> addresses = geo.getFromLocation(lat, lng, 1); 
      if (addresses.isEmpty()) { 
       endereco.setText("Waiting for Location"); 
      } 
      else { 
       if (addresses.size() > 0) { 
        Log.d(TAG,addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName()); 

       } 
      } 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 




    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras){ 
     //TODO Auto-generated method tub 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
     Toast.makeText(this, "Enabled new provider " + provider, 
       Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     Toast.makeText(this, "Disabled provider " + provider, 
       Toast.LENGTH_SHORT).show(); 
    } 



} 

的代码,我做了一对情侣在变化代码并设法让它工作。

解决问题的东西就是一点。

char[] buffer = new char[2048]; 
       Reader reader = new InputStreamReader(entity.getContent(), "UTF-8"); 
       while (true) { 
        int n = reader.read(buffer); 
        if (n < 0) { 
         break; 
        } 
        stringBuilder.append(buffer, 0, n); 
       } 

但是,由于我改变了很多东西,我会发布完整的代码下面。

package br.com.agenciaeisberg.qm; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.Reader; 

/** 
* Created by Usuário on 05/02/2015. 
*/ 
public class GPSActivity extends Activity implements LocationListener { 
    private TextView latituteField; 
    private TextView longitudeField; 
    private TextView endereco; 
    private LocationManager locationManager; 
    private String provider; 

    /** 
    * Called when the activity is first created. 
    */ 

    @Override 
    public void onCreate(Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.gps); 
     latituteField = (TextView) findViewById(R.id.TextView02); 
     longitudeField = (TextView) findViewById(R.id.TextView04); 
     endereco = (TextView) findViewById(R.id.Endereco); 

     //Get the Location Manager 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     //Define the criteria how to select location provider -> use 
     // default 

     Criteria criteria = new Criteria(); 
     provider = locationManager.getBestProvider(criteria,false); 
     Location location = locationManager.getLastKnownLocation(provider); 

     // Initialize the location fields 
     if (location != null){ 
      System.out.println("Provider " + provider + " has been selected"); 
      onLocationChanged(location); 
     }else{ 
      latituteField.setText("Locação não disponível"); 
      longitudeField.setText("Locação não disponível"); 
     } 
    } 

    /** 
    * Request updates at startup 
    */ 
    @Override 
    protected void onResume(){ 
     super.onResume(); 
     locationManager.requestLocationUpdates(provider, 400, 1, this); 
    } 

    /** 
    * Remove the LocationListener updates when Activity is paused 
    */ 
    @Override 
    protected void onPause(){ 
     super.onPause(); 
     locationManager.removeUpdates(this); 
    } 

    @Override 
    public void onLocationChanged(Location location){ 
     double lat = (location.getLatitude()); 
     double lng = (location.getLongitude()); 
     latituteField.setText(String.valueOf(lat)); 
     longitudeField.setText(String.valueOf(lng)); 


     // Encontrando Endereço 
     new EncontrarEndereco().execute(); 

    } 




    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras){ 
     //TODO Auto-generated method tub 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
     Toast.makeText(this, "Enabled new provider " + provider, 
       Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     Toast.makeText(this, "Disabled provider " + provider, 
       Toast.LENGTH_SHORT).show(); 
    } 

    class EncontrarEndereco extends AsyncTask<String, String, JSONObject> { 

     ProgressDialog pDialog = new ProgressDialog(GPSActivity.this); 

     @Override 
     protected void onPreExecute(){ 
      super.onPreExecute(); 
      pDialog.setMessage("Aguarde, enquanto buscamos seu endereço"); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 


     double lat = -19.971864410192393; 
     double lng = -43.97544760674483; 

     HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true&language=pt&region=BR&output=xml&oe=utf8"); 
     HttpClient client = new DefaultHttpClient(); 
     HttpResponse response; 
     StringBuilder stringBuilder = new StringBuilder(); 

     protected JSONObject doInBackground (String... args){ 
      try { 
       response = client.execute(httpGet); 
       HttpEntity entity = response.getEntity(); 

       char[] buffer = new char[2048]; 
       Reader reader = new InputStreamReader(entity.getContent(), "UTF-8"); 
       while (true) { 
        int n = reader.read(buffer); 
        if (n < 0) { 
         break; 
        } 
        stringBuilder.append(buffer, 0, n); 
       } 


       int b; 
       while ((b = reader.read()) != -1) { 
        stringBuilder.append((char) b); 
       } 
      } catch (ClientProtocolException e) { 
      } catch (IOException e) { 
      } 

      JSONObject jsonObject = new JSONObject(); 
      try { 
       jsonObject = new JSONObject(stringBuilder.toString()); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      return jsonObject; 
     } 

     protected void onPostExecute(final JSONObject jsonObject) { 
      // Dismiss a caixa de dialogo depois de buscar todos os items 


      String numero; 
      String rua; 
      String bairro; 
      String cidade; 
      String estado; 
      String pais; 
      String endereco_compelto; 

      pDialog.dismiss(); 

      Log.i("JSON string =>", jsonObject.toString()); 

      try { 
       String status = jsonObject.getString("status"); 
       Log.i("status", status); 

       if(status.equalsIgnoreCase("OK")){ 
        JSONArray results = jsonObject.getJSONArray("results"); 

        JSONObject r = results.getJSONObject(0); 
        JSONArray addressComponentsArray = r.getJSONArray("address_components"); 

        JSONObject addressComponents = addressComponentsArray.getJSONObject(0); 
        numero = addressComponents.getString("short_name"); 
        Log.i("Número", numero); 

        JSONObject addressComponents1 = addressComponentsArray.getJSONObject(1); 
        rua = addressComponents1.getString("long_name"); 
        Log.i("Rua", rua); 

        JSONObject addressComponents2 = addressComponentsArray.getJSONObject(2); 
        bairro = addressComponents2.getString("long_name"); 
        Log.i("Bairro ", bairro); 

        JSONObject addressComponents3 = addressComponentsArray.getJSONObject(3); 
        cidade = addressComponents3.getString("long_name"); 
        Log.i("Cidade ", cidade); 

        JSONObject addressComponents5 = addressComponentsArray.getJSONObject(5); 
        estado = addressComponents5.getString("short_name"); 
        Log.i("Estado ", estado); 

        JSONObject addressComponents6 = addressComponentsArray.getJSONObject(6); 
        pais = addressComponents6.getString("long_name"); 
        Log.i("Pais ", pais); 

        endereco_compelto = rua + ", " + numero + " - " + bairro + ", " + cidade + " - " + estado + ", " + pais; 

        endereco.setText(endereco_compelto); 

       } 




      }catch (JSONException e) { 
       Log.e("testing","Failed to load JSON"); 
       e.printStackTrace(); 
      } 


     } 


    } 


}