손장민

Current Location Editted

......@@ -5,7 +5,9 @@ import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import com.google.android.gms.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
......@@ -49,13 +51,10 @@ import com.google.android.gms.maps.model.MarkerOptions;
* Created by HYB on 2017. 10. 11..
*/
public class Map extends Fragment
implements OnMapReadyCallback ,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
public class Map extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
private Location lastLocation;
private static final LatLng DEFAULT_LOCATION = new LatLng(37.56, 126.97);
private static final String TAG = "googlemap_example";
private static final int GPS_ENABLE_REQUEST_CODE = 2001;
......@@ -79,12 +78,15 @@ public class Map extends Fragment
}
public void setCurrentLocation(Location location, String markerTitle, String markerSnippet) {
if ( currentMarker != null ) currentMarker.remove();
if ( location != null) {
public void setCurrentLocation(Location location, String markerTitle, String markerSnippet)
{
if (currentMarker != null)
{ currentMarker.remove(); }
if (location != null)
{
Log.i(TAG, " Got my Loc!! ");
//현재위치의 위도 경도 가져옴
LatLng currentLocation = new LatLng( location.getLatitude(), location.getLongitude());
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocation);
......@@ -119,16 +121,18 @@ public class Map extends Fragment
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View layout = inflater.inflate(R.layout.map, container, false);
mapView = (MapView)layout.findViewById(R.id.mapView);
mapView = (MapView) layout.findViewById(R.id.mapView);
mapView.getMapAsync(this);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener()
{
@Override
public void onPlaceSelected(Place place) {
public void onPlaceSelected(Place place)
{
Location location = new Location("");
location.setLatitude(place.getLatLng().latitude);
location.setLongitude(place.getLatLng().longitude);
......@@ -137,7 +141,8 @@ public class Map extends Fragment
}
@Override
public void onError(Status status) {
public void onError(Status status)
{
Log.i(TAG, "An error occurred: " + status);
}
});
......@@ -158,8 +163,8 @@ public class Map extends Fragment
super.onStop();
mapView.onStop();
if ( googleApiClient != null && googleApiClient.isConnected())
googleApiClient.disconnect();
if (googleApiClient != null && googleApiClient.isConnected())
{ googleApiClient.disconnect(); }
}
@Override
......@@ -175,8 +180,8 @@ public class Map extends Fragment
super.onResume();
mapView.onResume();
if ( googleApiClient != null)
googleApiClient.connect();
if (googleApiClient != null)
{ googleApiClient.connect(); }
}
@Override
......@@ -185,10 +190,12 @@ public class Map extends Fragment
super.onPause();
mapView.onPause();
if ( googleApiClient != null && googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, (com.google.android.gms.location.LocationListener) this);
if (googleApiClient != null && googleApiClient.isConnected())
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
googleApiClient.disconnect();
}
}
@Override
......@@ -204,12 +211,14 @@ public class Map extends Fragment
super.onDestroy();
mapView.onLowMemory();
if ( googleApiClient != null ) {
if (googleApiClient != null)
{
googleApiClient.unregisterConnectionCallbacks(this);
googleApiClient.unregisterConnectionFailedListener(this);
if ( googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, (com.google.android.gms.location.LocationListener) this);
if (googleApiClient.isConnected())
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
googleApiClient.disconnect();
}
}
......@@ -220,6 +229,7 @@ public class Map extends Fragment
{
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "An error occurred: onActivityCreated");
//액티비티가 처음 생성될 때 실행되는 함수
MapsInitializer.initialize(getActivity().getApplicationContext());
......@@ -227,24 +237,26 @@ public class Map extends Fragment
{
mapView.onCreate(savedInstanceState);
}
Log.i(TAG, "An error occurred: EndonActivityCreated");
}
@Override
public void onMapReady(GoogleMap googleMap)
{
//
// LatLng SEOUL = new LatLng(37.56, 126.97);
// MarkerOptions markerOptions = new MarkerOptions();
// markerOptions.position(SEOUL);
// markerOptions.title("서울");
// markerOptions.snippet("수도");
// googleMap.addMarker(markerOptions);
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));
// googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
//
// LatLng SEOUL = new LatLng(37.56, 126.97);
// MarkerOptions markerOptions = new MarkerOptions();
// markerOptions.position(SEOUL);
// markerOptions.title("서울");
// markerOptions.snippet("수도");
// googleMap.addMarker(markerOptions);
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));
// googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
// OnMapReadyCallback implements 해야 mapView.getMapAsync(this); 사용가능. this 가 OnMapReadyCallback
Log.i(TAG, "An error occurred: onMapReady");
this.googleMap = googleMap;
//런타임 퍼미션 요청 대화상자나 GPS 활성 요청 대화상자 보이기전에 지도의 초기위치를 서울로 이동
......@@ -256,117 +268,82 @@ public class Map extends Fragment
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// API 23 이상이면 런타임 퍼미션 처리 필요
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
// 사용권한체크
int hasFineLocationPermission = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION);
if ( hasFineLocationPermission == PackageManager.PERMISSION_DENIED) {
if (hasFineLocationPermission == PackageManager.PERMISSION_DENIED)
{
//사용권한이 없을경우
//권한 재요청
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
}
else
{
//사용권한이 있는경우
if ( googleApiClient == null) {
if (googleApiClient == null)
{
buildGoogleApiClient();
}
if ( ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
googleMap.setMyLocationEnabled(true);
}
}
} else {
}
else
{
if ( googleApiClient == null) {
if (googleApiClient == null)
{
buildGoogleApiClient();
}
googleMap.setMyLocationEnabled(true);
}
Log.i(TAG, "An error occurred: ENDonMapReady");
}
private void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(getActivity(), this)
.build();
Log.i(TAG, "An error occurred: buildGoogleApiClient");
googleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).addApi(Places.GEO_DATA_API).addApi(Places.PLACE_DETECTION_API).enableAutoManage(getActivity(), this).build();
googleApiClient.connect();
Log.i(TAG, "An error occurred: ENDbuildGoogleApiClient");
}
public boolean checkLocationServicesStatus() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
@Override
public void onLocationChanged(Location location)
{
Log.i(TAG, "onLocationChanged call..");
searchCurrentPlaces();
}
private void searchCurrentPlaces()
public boolean checkLocationServicesStatus()
{
Log.i(TAG, "An error occurred: checkLocationServicesStatus");
@SuppressWarnings("MissingPermission") PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(googleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>(){
@Override
public void onResult(@NonNull PlaceLikelihoodBuffer placeLikelihoods) {
int i = 0;
LikelyPlaceNames = new String[MAXENTRIES];
LikelyAddresses = new String[MAXENTRIES];
LikelyAttributions = new String[MAXENTRIES];
LikelyLatLngs = new LatLng[MAXENTRIES];
for(PlaceLikelihood placeLikelihood : placeLikelihoods) {
LikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
LikelyAddresses[i] = (String) placeLikelihood.getPlace().getAddress();
LikelyAttributions[i] = (String) placeLikelihood.getPlace().getAttributions();
LikelyLatLngs[i] = placeLikelihood.getPlace().getLatLng();
i++;
if(i > MAXENTRIES - 1 ) {
break;
}
}
placeLikelihoods.release();
Location location = new Location("");
location.setLatitude(LikelyLatLngs[0].latitude);
location.setLongitude(LikelyLatLngs[0].longitude);
setCurrentLocation(location, LikelyPlaceNames[0], LikelyAddresses[0]);
}
});
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Log.i(TAG, "An error occurred: ENDcheckLocationServicesStatus");
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
@Override
public void onProviderEnabled(String provider)
public void onLocationChanged(Location location)
{
Log.i(TAG, "onLocationChanged call..");
lastLocation = location;
if(currentMarker != null)
{
currentMarker .remove();
}
LatLng mlanglang = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mlanglang);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
@Override
public void onProviderDisabled(String provider)
{
currentMarker = googleMap.addMarker(markerOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(mlanglang));
googleMap.animateCamera(CameraUpdateFactory.zoomBy(10));
}
......@@ -374,71 +351,79 @@ public class Map extends Fragment
public void onConnected(@Nullable Bundle bundle)
{
if ( !checkLocationServicesStatus()) {
Log.i(TAG, "An error occurred: onConnected");
if (!checkLocationServicesStatus())
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("위치 서비스 비활성화");
builder.setMessage("앱을 사용하기 위해서는 위치 서비스가 필요합니다.\n" +
"위치 설정을 수정하십시오.");
builder.setMessage("앱을 사용하기 위해서는 위치 서비스가 필요합니다.\n" + "위치 설정을 수정하십시오.");
builder.setCancelable(true);
builder.setPositiveButton("설정", new DialogInterface.OnClickListener() {
builder.setPositiveButton("설정", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent callGPSSettingIntent =
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
public void onClick(DialogInterface dialogInterface, int i)
{
Intent callGPSSettingIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(callGPSSettingIntent, GPS_ENABLE_REQUEST_CODE);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener(){
builder.setNegativeButton("취소", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i) {
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
builder.create().show();
}
Log.i(TAG, "An error occurred: onConnected2");
LocationRequest locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL_MS);
locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_MS);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ( ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
} else {
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);
}
else
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
this.googleMap.getUiSettings().setCompassEnabled(true);
this.googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
Log.i(TAG, "An error occurred: onConnected3");
}
@Override
public void onConnectionSuspended(int i)
{
if ( i == CAUSE_NETWORK_LOST )
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: network lost.");
else if (i == CAUSE_SERVICE_DISCONNECTED )
Log.e(TAG,"onConnectionSuspended(): Google Play services " +
"connection lost. Cause: service disconnected");
if (i == CAUSE_NETWORK_LOST)
{ Log.e(TAG, "onConnectionSuspended(): Google Play services " + "connection lost. Cause: network lost."); }
else if (i == CAUSE_SERVICE_DISCONNECTED)
{ Log.e(TAG, "onConnectionSuspended(): Google Play services " + "connection lost. Cause: service disconnected"); }
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{
Log.i(TAG, "An error occurred: onConnectionFailed");
Location location = new Location("");
location.setLatitude(DEFAULT_LOCATION.latitude);
location.setLongitude((DEFAULT_LOCATION.longitude));
setCurrentLocation(location, "위치정보 가져올 수 없음",
"위치 퍼미션과 GPS활성 여부 확인");
setCurrentLocation(location, "위치정보 가져올 수 없음", "위치 퍼미션과 GPS활성 여부 확인");
Log.i(TAG, "An error occurred: ENDonConnectionFailed");
}
}
......