Android Geocoder not returning City

a 夏天 提交于 2019-12-11 21:20:59

问题


I need help. Im stuck in getting cityname using Geocoder api. Anthing that I did wrong here.

One thing that work is if I used this in the onLocationChanged(Location loc).

However that require me to update my coordinate by moving around. I only want to use coordinate from network.

Any help is very much appreciated.

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:


Try this it will give you address from the Location.

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

 }
 }


来源:https://stackoverflow.com/questions/18545853/android-geocoder-not-returning-city

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!