마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

GPSListener를 통해 받은 위치를 mapview에서 변경하여 보여주기

0 추천

안드로이드 버전 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();
}

 

Sprite_ZERO (470 포인트) 님이 2022년 2월 14일 질문

1개의 답변

0 추천
 
채택된 답변

GpsListener 생성자에 MapView를 전달하세요.

class GPSListener implements LocationListener {
       private final MapView mapView;
       public GPSListener(MapView mapView) {
          this.mapView = mapView;
       }
  
        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();

            // 여기에서 mapView 에 접근하여 필요한 처리.
        }
 
        public void onProviderDisabled(String provider) { }
        public void onProviderEnabled(String provider) { }
        public void onStatusChanged(String provider, int status, Bundle extras) { }
}


GpsListener를 생성할 때 MapView instance를 넘겨주세요.

GPSListener gpsListener = new GPSListener(googleMap);

 

MapView위에 마커를 표시하는 동작을 별도의 클래스로 분리한 다음에 MapView대신에 이걸 넘겨주셔도 좋을 것 같습니다.

public class MarkerHelper {

       private final MapView mapView;
       public MarkerDrawer(MapView mapView) {
          this.mapView = mapView;
       }

       public void showMarker(Location location) {
           if (location == null) return;

           latitude = location.getLatitude();
           longitude = location.getLongitude();
           curPoint = new LatLng(latitude, longitude);

           mapView.clear();

           markerOptions.title("현재위치");

           String newLat = String.format("%.2f", latitude);
           String newLong = String.format("%.2f", longitude);
           markerOptions.snippet("위도:"+ newLat + " 경도:" + newLong);
           markerOptions.position(curPoint);
           mapView.animateCamera(CameraUpdateFactory.newLatLngZoom(curPoint, 15));
           mapView.addMarker(markerOptions);
       }
 
}
private MarkerHelper markerHelper;

markerHelper = new MarkerHelper(googleMap);

GPSListener gpsListener = new GPSListener(markerHelper);

 

spark (227,510 포인트) 님이 2022년 2월 14일 답변
Sprite_ZERO님이 2022년 2월 14일 채택됨
바로 해결하였습니다.
정말 감사드립니다:)
...