안녕하세요! miTHON의 위치 정보 및 안드로이드 서비스 단 담당 강현지입니다.


구글 지도 API 활용하기 두번째 포스팅으로 찾아왔습니다!!!


이번 포스팅은 지난번 포스팅에 말씀드린대로 현재 위치 받아오기실시간 트래킹에 대해 살펴보려고 합니다.



[ 4단계: 현재 위치 받아오기 ]


현재 위치를 실시간으로 받아와서 지도에 마커를 표시하는 코드를 아래와 같이 작성하였습니다. 


/**
* 현재 위치정보 조회.
*
* @return
*/
public Maybe<Location> get_현재위치정보() {
try {
// 권한 체크.
CheckUtil.Check(ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED, "[ACCESS_FINE_LOCATION] 권한체크 에러", Exception.class);
CheckUtil.Check(ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED, "[ACCESS_COARSE_LOCATION] 권한체크 에러", Exception.class);

// 위치정보 조회.
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

// 위치 정보 사용여부 조회.
{
CheckUtil.Check(get_위치정보_요청가능_여부(locationManager), "위치정보 사용불가능 상태", Exception.class);
}

// 네트워크 정보로부터 데이터 조회.
{
// 네트워크 정보로 부터 위치값 가져오기
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES
, this
);

if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
}

// GPS 정보로부터 데이터 조회.
{
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);

if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}

} catch (Exception e) {
Log.e(MiRunConstDefinition.LOG_NAME, "위치정보 획득 실패", e);
}

return MaybeUtil.JustNullable(location);
}
/**
* 마커 그리기
*
* @param myLocationMaybe
*/
public void setDrawMaker(Maybe<Location> myLocationMaybe) {

MaybeUtil.Subscribe(myLocationMaybe,

location -> {

// Creating a LatLng object for the current location
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

CameraPosition cp = new CameraPosition.Builder().target((latLng)).
zoom(17).
build();

// Showing the current location in Google Map
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));

// 기존 마커 삭제.
if (marker != null) {
marker.remove();
}

// 마커 설정.
MarkerOptions optFirst = new MarkerOptions().
position(latLng).
icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_marker_pink)).
title(MiRunResourceUtil.GetString(R.string.label_record_current_position));

marker = mGoogleMap.addMarker(optFirst);
},
() -> MiRunViewUtil.ShowToast(R.string.label_emergency_request_location_fail));
}






[ 5단계: 실시간 트래킹 ]


실시간 위치정보를 받아 트래킹 라인을 그리는 코드는 아래와 같습니다.


/**
* 지역 정보 목록 세팅.
*
* @param locationList
* @param myLocationMaybe
*/
public void setLocationList(@NonNull List<LocationConcreteVO> locationList, Maybe<Location> myLocationMaybe) {
// TODO khj1219

// 위도경도 목록 제작.
List<LatLng> latLngList = new ArrayList<>();
{

Observable.fromIterable(locationList).
forEach(vo -> {
// 위도 경도 처리.
latLngList.add(new LatLng(vo.getLatitude(), vo.getLongitude()));
Log.d(MiRunConstDefinition.LOG_NAME, String.format("초기화용 데이터 -> 위도 : %f, 경도 : %f, 시간 : %d",
vo.getLatitude(), vo.getLongitude(), vo.getTime()));
});

myLocationMaybe.
map(location -> new LatLng(location.getLatitude(), location.getLongitude())).
subscribe(latLngList::add);
}

// 마지막 라인 마커찍기.
{
if (!ContainerUtil.IsEmpty(latLngList)) {
setDrawMaker(myLocationMaybe);
}
}

AsyncBuilder.Create((FlowableEmitter<Double> emitter) -> {
if(latLngList.size() > 1){
Double result = getRecordDistance(latLngList);
emitter.onNext(result);
emitter.onComplete();
}
}).doOnNext(result -> {
// 거리 업데이트.
if(!Double.isNaN(result)){
setTextByDistance(result);
setTextByDonation(result * MiRunConstDefinition.CONST_DONATION.RUN_PER_REWARD);
}
}).run();

// 달리는 경로 polyline 생성.
drawRunningPolyline(latLngList);
}
/**
* 달리는 경로 polyline 생성(pink)
*
* @param runningPoints
*/
public void drawRunningPolyline(List<LatLng> runningPoints){
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(MiRunResourceUtil.GetColor(R.color.color_path_pink));
polylineOptions.width(7);
polylineOptions.addAll(runningPoints);
mGoogleMap.addPolyline(polylineOptions);
}




이것으로 구글 지도 API 활용하기 5단계에 대해 모두 살펴보았습니다.


트래킹의 경우 테스트가 매우 힘들었지만 결과적으로 앱이 잘 나와서 매우 행복합니다.


드디어 발표가 내일인데 좋은 결과 있었으면 좋겠네요.


아직까지 열심히 디비 작업중이신 우리 유감독님 더불어 피티엥 혼신의 힘을 다하고 계신 남배우님 정말 존경하고 조금만 힘내세요!!!


우리 모두 화이팅 입니다~~


반응형
Posted by N'