안드로이드 버전 Arctic fox 2020.3.1 patch4
안녕하세요
저는 mapView에 구글 지도를 띄운 후, requestLocationUpdates를 통해서는 지속적으로 위치정보를 업데이트 하며 그 위치를 mapView에도 적용하는 프로그램을 하고 있습니다.
제가 mapView에 위치를 띄우고 requestLocationupdates를 통해 지속적으로 위치 업데이트 상황을 받아서 toast 메시지로 나타내는 것까지는 했는데 그 위치를 mapView에 적용하는 부분에서는 nullPointerErr가 발생하여 실패합니다.
어떻게 해야 위치를 받고 위치상태를 지도에도 업데이트 할 수 있을까요?
fragment 위 mapveiw에 구글지도를 띄우며, 버튼을 누르면 현재 위치로 이동하는 프로그램입니다.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
try {
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
curPoint = new LatLng(latitude, longitude);
googleMap.clear();
markerOptions.title("현재위치");
String newLat = String.format("%.2f", latitude);
String newLong = String.format("%.2f", longitude);
markerOptions.snippet("위도:"+ newLat + " 경도:" + newLong);
markerOptions.position(curPoint);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curPoint, 15));
googleMap.addMarker(markerOptions);
}
GPSListener gpsListener = new GPSListener();
long minTime = 10000;
float minDistance = 0;
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, gpsListener);
} catch (SecurityException e){
e.printStackTrace();
}
}
});
class GPSListener implements LocationListener {
public void onLocationChanged(Location location){
latitude = location.getLatitude();
longitude = location.getLongitude();
String message = "최근 위치 -> Latitude : " + latitude + "\nLongitude:" + longitude;
Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider) { }
public void onProviderEnabled(String provider) { }
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
public void showToast(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
}