プログラムで GPS を使用して現在の位置を取得する必要があります。どうすれば実現できますか?
ベストアンサー1
現在の位置の GPS 座標を取得するための、ステップバイステップの説明を含む小さなアプリケーションを作成しました。
完全なサンプルソースコードはAndroidで現在の位置の座標、都市名を取得する。
仕組みをご覧ください:
必要なのは、マニフェスト ファイルに次の権限を追加することだけです。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
次のように LocationManager インスタンスを作成します。
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
GPSが有効になっているかどうかを確認します。
次に、LocationListener を実装して座標を取得します。
LocationListener locationListener = new MyLocationListener(); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
これを行うためのサンプルコードは次のとおりです。
/*---------- Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*------- 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();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
editLocation.setText(s);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}