날뛰는 코드

구글 맵 내위치 받아오기 (17/08/19) 본문

안드로이드/구글 맵

구글 맵 내위치 받아오기 (17/08/19)

미 냉 2017. 8. 19. 21:21

참고 예제 코드.

 

https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MyLocationDemoActivity.java

 

 

https://developers.google.com/maps/documentation/android-api/location?hl=ko

 

 

1.

 

private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

 

2. implements 추가

public class MainActivity extends AppCompatActivity
implements
GoogleMap.OnMyLocationButtonClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback{
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
return false;
}

OnMyLocationBttonClickListener 은 이거필요하네

 

3.

private boolean mPermissionDenied = false;

4. OnMapReady에 추가

map.setOnMyLocationButtonClickListener(this);
enableMyLocation();

5. 함수 추가

private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (map != null) {
// Access to the location has been granted to the app.
map.setMyLocationEnabled(true);
}
}

6. 여기서 PermissionUtils가 구글에서 따로 만든 거라 깃허브에서 가져옴

 

https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/PermissionUtils.java

 

 

가져와 message dilog부분 걍 문장으로 바꾸고,  조금 바꾸니 빨간 줄은 없어짐.

 

7. 나머지 다 고치면서 떄려박음

 

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}

if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}

private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}

버튼 생기고됨.

 

결론.

1. 갓구글

2. 갓깃허브

3. 갓스택오버플로우

 

* 내위치 얻어오는게 생각보다 안쉽네 함수 한두개면 될 줄 알았는데

 

 

http://duzi077.tistory.com/122

나중에 참고할 것 같은 곳

 


 

-- 내 위치정보 데이터로 받아야되면 이거 써야되나본데

 

참고로 My Location 계층은 데이터를 반환하지 않습니다. 프로그래밍 방식으로 위치 데이터에 액세스하려면 Location API를 사용합니다.

Google Play 서비스 Location API

Android 애플리케이션에 위치 인식을 추가하려면 Google Play 서비스 Location API를 사용하는 것이 좋습니다. 이 API에는 다음 기능이 포함되어 있습니다.

  • 기기의 위치를 판별합니다.
  • 위치 변경을 수신합니다.
  • 기기가 이동 중일 때 교통수단을 판별합니다.
  • 지오펜스(geofence)라는 사전 정의된 지리적 지역을 생성, 모니터링합니다.

위치 API를 사용하면 효율적으로 전력을 소비하는 위치 인식 애플리케이션을 쉽게 제작할 수 있습니다. Google Maps Android API처럼 Location API도 Google Play 서비스 SDK의 일부로 배포됩니다. Location API에 대한 자세한 내용은 Android 교육 과정 위치를 인식하는 앱 제작 또는 Location API 참조를 참조하세요. 코드 예시는 Google Play 서비스 SDK의 일부로 포함되어 있습니다.

 

 

 

 

 

 




 

 

 

*** 하다보니까 위치 받아오는거 해버리고 싶었다.

 

double -> string

String.format(Locale.KOREA,"%.3f",latitude)  이게 더 나은것 같다. Double.toString()보다

 

 

참고 예제 코드

http://blog.naver.com/PostView.nhn?blogId=netrance&logNo=110174035971

 

 

*참고


위치 정보를 구하는 방법

 

1. 먼저 위치 정보를 구하기 위한 권한을 설정합니다. 방법은 여기를 참고 하세요.

 

2. LocationListener 인터페이스를 구현하는 클래스를 정의하세요. 이 클래스는 위치 정보를 위치 공급자로부터 지속적으로 받아오는 역할을 합니다. 오버라이드 해야 하는 메소드들은 다음과 같습니다.

 

  • void onLocationChanged(Location location)
    • 위치 정보를 가져올 수 있는 메소드입니다.
    • 위치 이동이나 시간 경과 등으로 인해 호출됩니다.
    • 최신 위치는 location 파라메터가 가지고 있습니다.
    • 최신 위치를 가져오려면, location 파라메터를 이용하시면 됩니다.
  • void onProviderDisabled(String provider)
    • 위치 공급자가 사용 불가능해질(disabled) 때 호출 됩니다.
    • 단순히 위치 정보를 구한다면, 코드를 작성하실 필요는 없습니다.
  • void onProviderEnabled(String provider)
    • 위치 공급자가 사용 가능해질(enabled) 때 호출 됩니다.
    • 단순히 위치 정보를 구한다면, 코드를 작성하실 필요는 없습니다.
  • void onStatusChanged(String provider, int status, Bundle extras)

 

위치 공급자가 GPS이고, 갱신에 필요한 최소 시간 간격이 1초(1000 milliseconds)이며, 최소 거리가 10미터인 위치 갱신을 요구한다고 가정해 봅시다. 코드는 다음과 같습니다. 리스너는 2에서 구현한 것을 listener 파라메터에 대입하였습니다.

 

lm.requestLocationUpdates(
    LocationManager.GPS_PROVIDER,
    1000,
    10,
    locationListener

 

 


 

1. 위치 받을 변수 선언

private Location lastKnownLocation = null ;

2. 내 위치 바뀔때 마다 위치 받아올 함수 위치 바뀔 떄 마다 setText에 위치 표시하고 Toast 표시

LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Get the last location.
lastKnownLocation = location;


lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
1000,
10,
locationListener
);
tv.setText(String.format(Locale.KOREA,"%.3f",lastKnownLocation.getLatitude())+ " , "+ String.format(Locale.KOREA,"%.3f",lastKnownLocation.getLongitude()));
Toast.makeText(getApplicationContext(), String.format(Locale.KOREA,"%.3f",lastKnownLocation.getLatitude())+ " , "+ String.format(Locale.KOREA,"%.3f",lastKnownLocation.getLongitude()), Toast.LENGTH_LONG).show();
// lm.removeUpdates(locationListener);

}// onLocationChanged

3. GPS 버튼 처음누르면 위치 받아오고 계속 위치를 갱신한다.

     두번 누르면 위치 갱신 멈춘다.

public boolean onMyLocationButtonClick() {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
if(gps_cnt==0) {
Toast.makeText(this, "GPS 추적 ON", Toast.LENGTH_SHORT).show();
gps_cnt++;
}
else
{
lm.removeUpdates(locationListener);
Toast.makeText(this, "GPS 추적 OFF", Toast.LENGTH_SHORT).show();
gps_cnt=0;
}
return false;
}

 

 

** 결과

 

 

     

 

 

 

 

https://github.com/littlecold2/googlemap_test

Comments