안드로이드 위도 경도로 주소 불러 오기

안드로이드 위도 경도로 주소 불러 오기

QA

안드로이드 위도 경도로 주소 불러 오기

본문

버튼을 클릭하면 텍스트뷰에 위도 경도가 표시되는것까지 완료 되었씁니다

가져온 위도 경도로  textview 로 주소를 불러 오려고 하는데.. 잘 안되네요 



TextView tv1;

tv1= (TextView) findViewById(R.id.textView1); 

tv1.setText(getAddress);

이런식으로 한는 거라는데..  아닌가요? 왜 안되지 ㄷㄷ


지금 위도 경도는 버튼을 클릭하면 불러와 지는데요

앱을 실행하면 버튼 클릭 없이 위도 경도 주소가 자동으로 화면에 보여지게 하고 싶습니다.


아래는 위,경도로 주소변환 하는 코드입니다

/** 위도와 경도 기반으로 주소를 리턴하는 메서드*/

    public String getAddress(double latitude, double longitude){

        String address = null;


        //위치정보를 활용하기 위한 구글 API 객체

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());


        //주소 목록을 담기 위한 HashMap

        List<Address> list = null;

        try{

            list = geocoder.getFromLocation(latitude, longitude, 1);

        } catch(Exception e){

            e.printStackTrace();

        }

        if(list == null){

            Log.e("getAddress", "주소 데이터 얻기 실패");

            return null;

        }

        if(list.size() > 0){

            Address addr = list.get(0);

            address = addr.getCountryName() + " "

                    + addr.getPostalCode() + " "

                    + addr.getLocality() + " "

                    + addr.getThoroughfare() + " "

                    + addr.getFeatureName();

        }

        return address;

    }


MainActivity.java
public class MainActivity extends AppCompatActivity {

private Button btnShowLocation;
private TextView txtLat;
private TextView txtLon;



// GPSTracker class
private GpsInfo gps;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);




if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION },
0 );
}


btnShowLocation = (Button) findViewById(R.id.btn_start);
txtLat = (TextView) findViewById(R.id.Latitude);
txtLon = (TextView) findViewById(R.id.Longitude);



// GPS 정보를 보여주기 위한 이벤트 클래스 등록
btnShowLocation.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
gps = new GpsInfo(MainActivity .this);
// GPS 사용유무 가져오기
if (gps.isGetLocation()) {

double latitude = gps.getLatitude();
double longitude = gps.getLongitude();


txtLat.setText(String.valueOf(latitude));
txtLon.setText(String.valueOf(longitude));

Toast.makeText(
getApplicationContext(),
"당신의 위치 - \n위도: " + latitude + "\n경도: " + longitude ,
Toast.LENGTH_LONG).show();
} else {
// GPS 를 사용할수 없으므로
gps.showSettingsAlert();
}
}


});
}

}





GpsInfo.java
public class GpsInfo extends Service implements LocationListener {
private final Context mContext;

// 현재 GPS 사용유무
boolean isGPSEnabled = false;

// 네트워크 사용유무
boolean isNetworkEnabled = false;

// GPS 상태값
boolean isGetLocation = false;

Location location;
double lat; // 위도
double lon; // 경도

// 최소 GPS 정보 업데이트 거리 10미터
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;

// 최소 GPS 정보 업데이트 시간 밀리세컨이므로 1분
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;

protected LocationManager locationManager;

public GpsInfo(Context context) {
this.mContext = context;
getLocation();
}

public Location getLocation() {
try {

locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

// GPS 정보 가져오기
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// 현재 네트워크 상태 값 알아오기
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( mContext, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}

if (!isGPSEnabled && !isNetworkEnabled) {
// GPS 와 네트워크사용이 가능하지 않을때 소스 구현
} else {
this.isGetLocation = true;
// 네트워크 정보로 부터 위치값 가져오기
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);

if (location != null) {
// 위도 경도 저장
lat = location.getLatitude();
lon = location.getLongitude();
}
}
}

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);
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
}
}
}



}

} catch (Exception e) {
e.printStackTrace();
}
return location;
}

/**
* GPS 종료
* */
public void stopUsingGPS(){
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( mContext, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
if(locationManager != null){
locationManager.removeUpdates(GpsInfo.this);
}
}

/**
* 위도값을 가져옵니다.
* */
public double getLatitude(){
if(location != null){
lat = location.getLatitude();
}
return lat;
}

/**
* 경도값을 가져옵니다.
* */
public double getLongitude(){
if(location != null){
lon = location.getLongitude();
}
return lon;
}



/**
* GPS 나 wife 정보가 켜져있는지 확인합니다.
* */
public boolean isGetLocation() {
return this.isGetLocation;
}

/**
* GPS 정보를 가져오지 못했을때
* 설정값으로 갈지 물어보는 alert 창
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

alertDialog.setTitle("GPS 사용유무셋팅");
alertDialog.setMessage("GPS 셋팅이 되지 않았을수도 있습니다. \n 설정창으로 가시겠습니까?");

// OK 를 누르게 되면 설정창으로 이동합니다.
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// Cancle 하면 종료 합니다.
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

alertDialog.show();
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}

public void onLocationChanged(Location location) {

}

public void onStatusChanged(String provider, int status, Bundle extras) {

}

public void onProviderEnabled(String provider) {

}

public void onProviderDisabled(String provider) {

}
 


















이 질문에 댓글 쓰기 :

답변을 작성하시기 전에 로그인 해주세요.
전체 109
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT