我继续使用以下代码将Geocoder定义为未定义。我想简单地从lat和long获取一个地方的地址。行Geocoder geocoder = new Geocoder(this,Locale.ENGLISH);总是回归原来的。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 600000, 1000, mlocListener);
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
currentLatitude = loc.getLatitude();
currentLongitude = loc.getLongitude();
try {
List<Address> addresses = geocoder.getFromLocation(currentLatitude, currentLongitude, 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!");
}
答案 0 :(得分:1)
那是因为它未定义:http://developer.android.com/reference/android/location/Geocoder.html显示了2个构造函数。一个接受Context,另一个接受Context和Locale,但关键是你在MyLocationListener
类中创建它。试试这个:
Geocoder geocoder = new Geocoder(<ACTIVITY CLASS NAME>.this, Locale.ENGLISH);
代替。
出于性能原因,您可能希望在Geocoder
类的构造函数中创建MyLocationListener
的单个实例,而不是每次获得位置更新时都生成一个。