我已經實現了這個代碼來顯示基於GPS的地址。經度和緯度工作正常(在屏幕上出現),但是,它的立場「沒有地址找到」的地址。請看這個代碼並指出任何錯誤。由於如何從經度和緯度獲取地址?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find__location);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager =(LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
//String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
//buttons assigned
Button mainMenuBtn = (Button) findViewById(id.mainMenuBtn);
mainMenuBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private final LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
};
private void updateWithNewLocation(Location location) {
String latLong;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "no address found";
if(location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLong = "Lat: "+lat+"\nLong: "+lng;
//double latitude = location.getLatitude();
//double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this,Locale.getDefault());
try{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0){
Address address = addresses.get(0);
for(int i=0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}catch (IOException e){}
}else{
latLong = "No location found";
}
myLocationText.setText("Your coordinates are:\n"+latLong + "\n"+addressString);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.find__location, menu);
return true;
}
}