現在地を表示したい

現在地を取得して地図上に表示したいので調べた。

現在地の取得&表示

うまく自分の中でまとまってないけど、できはした。権限の話やらなんやら。

うまく言葉で書けないから、ソースだけ書いとこ。

double lat = 0;
double lon = 0;
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
GPSLocationListener locationlistener = new GPSLocationListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
    ActivityCompat.requestPermissions(this, permissions, 1000);
    return;
}
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationlistener);
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == 1000 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        GPSLocationListener locationlistener = new GPSLocationListener();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationlistener);
    }
}
private class GPSLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        lat = location.getLatitude();
        lon = location.getLongitude();

        LatLng latlon = new LatLng(lat, lon);

        marker.setPosition(latlon);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latlon));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }
}

色々あった。

参考

[affi id=2]

https://qiita.com/hotdrop_77/items/bb8c97a3c197ee4f44df#4-gps%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6%E7%8F%BE%E5%9C%A8%E4%BD%8D%E7%BD%AE%E3%82%92%E5%88%9D%E6%9C%9F%E8%A1%A8%E7%A4%BA%E3%81%99%E3%82%8B%EF%BC%92%E5%9B%9E%E7%9B%AE

https://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(java.lang.String,%20long,%20float,%20android.location.LocationListener)

http://www.asahi-net.or.jp/~gq4r-msm/html/k-age63/android/html/1800a-gps.html

カテゴリー: のーと タグ: , , , , , パーマリンク

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です