gpt4 book ai didi

android - 如何在android中获取国家名称?

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:51 31 4
gpt4 key购买 nike

您好,我正在使用 android。我已经创建了一个 GPS 应用程序来获取当前位置。现在我如何从纬度和经度值中获取国家/地区名称?可能吗 ?请帮助我,谢谢 :)

这是我使用的代码

 public class AndroidGPSTrackingActivity extends Activity {

Button btnShowLocation;

// GPSTracker class
GPSTracker gps;
String countryCode,countryName;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);

// check if GPS enabled
if(gps.canGetLocation()){

double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.i("location", " "+latitude+" "+longitude);
// \n is for new line
try
{Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(latitude,longitude, 1);
if (addresses.size() > 0)
Toast.makeText(getApplicationContext(), "name "+addresses.get(0).getLocality(),Toast.LENGTH_SHORT).show();

//System.out.println(addresses.get(0).getLocality());
}

catch (IOException e) {

e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude+countryName +" "+countryCode, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}

}
});
}

}

最佳答案

    String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
@SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name = addresses.get(0).getCountryName();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();

关于android - 如何在android中获取国家名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23080016/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com