Android Google Maps v2で現在地を表示する
はじめに
AndroidでGoogle Map V2を使用して、現在地を表示します。
前提
以下の記事を参考にしてプロジェクトを作成します。
wanouri.hatenablog.com
Activityを変更
- システムサービスより、GPS_PROVIDER、NETWORK_PROVIDERを使用できるようにします。
- Android 6.0以降は、システムサービスを使用する際にパーミッションチェックをしなければなりません。
- 設定されていない場合、ACTION_LOCATION_SOURCE_SETTINGSで設定画面(パーミションリクエスト)を呼び出します。
MapsActivity.java
public class MapsActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private GoogleMap mMap; private LocationManager locationManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } private void locationStart() { locationManager = (LocationManager)getSystemService(LOCATION_SERVICE); if (locationManager != null && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.d("debug", "location manager Enabled ( GPS_PROVIDER )"); } else if (locationManager != null && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { Log.d("debug", "location manager Enabled ( NETWORK_PROVIDER )"); } else { Intent settingIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(settingIntent); Log.d("debug", "not gpsEnable or network, startActivity"); } // Perform permission checks if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // requests permissions to be granted to this application. // The permission dialog is displayed here. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,},1000); Log.d("debug", "checkSelfPermission false"); return; } // register location update using GPS_PROVIDER. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,50,this); // register location update using NETWORK_PROVIDER. locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000,50,this); }
- ユーザーがパーミッションリクエストで応答すると、以下のメソッドが呼び出されます。
- ユーザーにて、パーミッションが許可されると再度locationStartを呼び出して、GPS_PROVIDER、NETWORK_PROVIDERの使用を許可します。
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults ) { if (requestCode == 1000) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d("debug", "checkSelfPermission true"); locationStart(); } else { Toast toast = Toast.makeText(this, "I can not do anything more than this", Toast.LENGTH_SHORT); toast.show(); } } }
地図の準備ができた
- 地図の準備ができると、onMapReayがコールされます。
- パーミッションチェックにて許可されていれば、現在地を表示します。
@Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,},1000); } else { locationStart(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,50,this); } }
常に現在地を表示する
- 常に現在地を表示して、マーカーを表示するようにします。
- 17 と記述している箇所はズームレベル値です。
@Override public void onLocationChanged(Location location) { setCurrentLocation(location); } public void setCurrentLocation(Location location) { try { LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); mMap.clear(); mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in current location")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17)); } catch (Exception e){ Toast toast = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT); toast.show(); } }