0

我使用下面手机上的代码获取地址{国家、街道、城市},但它不适用于许多输入,为什么?有时会崩溃。请如何通过将经度和纬度传递给将所有可用地址返回到该经度和纬度的方法来获取完整地址。你能不能给我答案以获得最好的结果。帮我。

 import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Get_Location_Name extends Activity implements OnClickListener {
private EditText ET1;
private EditText ET2;
private TextView TV1;
private Button B1;
static String result ="";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.location_name);
    ET1=(EditText)this.findViewById(R.id.ET1_location_name);
    ET2=(EditText)this.findViewById(R.id.ET2_location_name);
    TV1=(TextView)this.findViewById(R.id.TV1_Location_name);
    B1=(Button)this.findViewById(R.id.B1_Location_name);
    B1.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {

    String s=null;
    if(!ET1.getText().toString().isEmpty() && !ET2.getText().toString().isEmpty())
    {
            if(this.isOnline())
            {

                for(int i=0;i<=10;i++)
                {
                    s=getAddressFromLocation(Double.parseDouble(ET2.getText().toString()),
                    Double.parseDouble(ET1.getText().toString()),this);
                }
            if(s!=null)
                {
                Log.d("ssss","s"+s);
                TV1.setText(s);
                }
            else
                TV1.setText("s is null");
            }
            else
                TV1.setText("no internet connection");

    }
    else
        TV1.setText("Enter the Lat. and Lon.");



}

public boolean isOnline() {
   // code to check connectivity // it works fine(no problems)
}

这是我要修改的方法

public static String getAddressFromLocation(final double lon,final double lat, final Context context) 
{

      Thread thread = new Thread() {
   @Override public void run() 
    {

       Geocoder geocoder = new Geocoder(context, Locale.getDefault());   

       try {
           List<Address> list = geocoder.getFromLocation(
                   lat, lon, 1);
           if (list != null && list.size() > 0) 
               {
               Address address = list.get(0);
               result = " "+address.getAddressLine(0) + ", " + address.getLocality()+","+address.getCountryName();
                   }
           } 
        catch (IOException e)
           {
           Log.e("fafvsafagag", "Impossible to connect to Geocoder", e);
           } 
    }
 };
 thread.start();
 return result;
  }

  }

请回答我的问题。

4

1 回答 1

1

有一个已知问题是 Geocoder 并不总是返回值。请参阅Geocoder 并不总是返回值,并且geocoder.getFromLocationName 仅返回 null。您可以尝试在 for 循环中发送 3 次请求。它应该能够至少返回一次。如果不是,则可能是连接问题,也可能是服务器未回复您的请求等其他问题。对我来说,有时即使它连接到互联网,它也不会返回任何东西。然后,我每次都使用这种更可靠的方式来获取地址:

//lat, lng are Double variables  containing latitude and longitude values. 
public JSONObject getLocationInfo() {
        //Http Request
        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
            } catch (IOException e) {
        }
                //Create a JSON from the String that was return.
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

我调用函数如下获取完整地址:

JSONObject ret = getLocationInfo(); //Get the JSON that is returned from the API call
JSONObject location;
String location_string;
//Parse to get the value corresponding to `formatted_address` key. 
try {
    location = ret.getJSONArray("results").getJSONObject(0);
    location_string = location.getString("formatted_address");
    Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
    e1.printStackTrace();

}

您可以在内部AsyncTask或新线程中调用它。我也用过Asynctask。希望这会有所帮助。这对我有用。如果您将 URL 替换为纬度和经度坐标,并在 Web 浏览器中查看返回的 JSON 对象。你会看到刚刚发生了什么。

于 2013-07-23T19:58:29.827 回答