Android Geocoder没有返回City

时间:2013-08-31 07:48:05

标签: android geolocation google-geocoder

我需要帮助。我坚持使用Geocoder api获取cityname。 Anthing我在这里做错了。

有一件事是如果我在onLocationChanged(位置loc)中使用它。

然而,这要求我通过四处走动来更新我的坐标。我只想使用网络坐标。

非常感谢任何帮助。

public void DisCityName(Location loc){
    /*----------to get City-Name from coordinates ------------- */
    String cityName=null;                 
    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());                  
    List<Address>  addresses;  
    try {  
    addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);  
    if (addresses.size() > 0)  
    System.out.println(addresses.get(0).getLocality());  
    cityName=addresses.get(0).getLocality();  
    } catch (IOException e) {                 
    e.printStackTrace();  
    } 

    Toast.makeText(getBaseContext(),
        "\n\nMy Currrent City is: "+cityName
        +"\nLatitude: "+loc.getLatitude()
        +"\nLongitude: "+loc.getLongitude(),
        Toast.LENGTH_SHORT).show();}

1 个答案:

答案 0 :(得分:4)

试试这个,它会从位置给你地址。

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!");
 }

 }
 }