Please Enable JavaScript!
Gon[ Enable JavaScript ]

반응형

안드로이드(Android) 현재 GPS 정보를 알아와 구글맵에 마커 표시하기

 

환경 : Eclipse Mars, Android 4.2.2

 

이번에는 현재 자신의 위치값을 가져와서 구글맵 으로 이동하고, 그 위치에 아이콘을 마크업 합니다. GPS 를 가져오는 클래스는 [안드로이드(Android) GPS 정보 알아오기] 이전 기사를 참조하시기 바랍니다.

 

 

 

GpsInfo 클래스의 전체 내용입니다. GPS 현재 위치를 알아오기 위해 만든 클래스 입니다. 이 클래스를 만드시고 아래에서 참고 하시면 됩니다.

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

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_UPDATES = 10;

	// GPS 정보 업데이트 시간 1/1000
	private static final long MIN_TIME_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);

			isGPSEnabled = locationManager
					.isProviderEnabled(LocationManager.GPS_PROVIDER);

			isNetworkEnabled = locationManager
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

			if (!isGPSEnabled && !isNetworkEnabled) {
			} else {
				this.isGetLocation = true;
				if (isNetworkEnabled) {
					locationManager.requestLocationUpdates(
							LocationManager.NETWORK_PROVIDER,
							MIN_TIME_UPDATES,
							MIN_DISTANCE_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_UPDATES,
										MIN_DISTANCE_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 (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;
	}

	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 설정창으로 가시겠습니까?");

		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);
					}
				});
		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) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String provider, int status,
			Bundle extras) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}
}

 

먼저 GpsInfo 클래스를 사용하여 현재 위치 정보를 가져옵니다. 가져와서 isGetLocation() 함수로 제대로 가져왔는지 판단합니다.

 

GpsInfo gps = new GpsInfo(CurrentMapActivity.this);
// GPS 사용유무 가져오기
if (gps.isGetLocation()) {

}

 

GpsInfo 에서 위도 경도를 가져와서 LatLng 객체를 생성합니다. 그리고 moveCamera() 로 현재 위치로 이동합니다. animateCamera() 는 줌값을 줘서 확대합니다.

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

// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);

// Showing the current location in Google Map
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

// Map 을 zoom 합니다. 
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(13));

 

마커 생성을 위해 MarkerOptions 객체를 생성합니다. MarkerOptions 속성값에 title 는 마커위에 생성되는 제목이고 간단 내용은 snippet 에 셋팅합니다. 모두 셋팅한후 GoogleMap addMarker 함수로 마커를 표시 합니다.

 

// 마커 설정.
MarkerOptions optFirst = new MarkerOptions();
optFirst.position(latLng);// 위도 • 경도
optFirst.title("Current Position");// 제목 미리보기
optFirst.snippet("Snippet");
optFirst.icon(BitmapDescriptorFactory.fromResource(
                  R.drawable.ic_launcher));
mGoogleMap.addMarker(optFirst).showInfoWindow();

 

아래는 메인화면을 생성한 레이아웃 xml 입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/map"
        android:name="com.example.GoogleMapVersion2.Fragment"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </fragment>

</RelativeLayout>

 

메인 activity 의 전체 소스입니다.

 

import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class CurrentMapActivity extends FragmentActivity implements
		OnMapClickListener {

	private GoogleMap mGoogleMap;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// BitmapDescriptorFactory 생성하기 위한 소스 
		MapsInitializer.initialize(getApplicationContext());
		
		init();
	}

	/** Map 클릭시 터치 이벤트 */
	public void onMapClick(LatLng point) {

		// 현재 위도와 경도에서 화면 포인트를 알려준다
		Point screenPt = mGoogleMap.getProjection().toScreenLocation(point);

		// 현재 화면에 찍힌 포인트로 부터 위도와 경도를 알려준다.
		LatLng latLng = mGoogleMap.getProjection().fromScreenLocation(screenPt);

		Log.d("맵좌표", "좌표: 위도(" + String.valueOf(point.latitude) + "), 경도("
				+ String.valueOf(point.longitude) + ")");
		Log.d("화면좌표", "화면좌표: X(" + String.valueOf(screenPt.x) + "), Y("
				+ String.valueOf(screenPt.y) + ")");
	}
	
	/**
	 * 초기화
	 * @author 
	 */
	private void init() {
		
		GooglePlayServicesUtil.isGooglePlayServicesAvailable(CurrentMapActivity.this);
		mGoogleMap = ((SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map)).getMap();
		
		// 맵의 이동 
		//mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
		
		GpsInfo gps = new GpsInfo(CurrentMapActivity.this);
		// GPS 사용유무 가져오기
		if (gps.isGetLocation()) {
			double latitude = gps.getLatitude();
			double longitude = gps.getLongitude();
			
			// Creating a LatLng object for the current location
	        LatLng latLng = new LatLng(latitude, longitude);

	        // Showing the current location in Google Map
	        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
	        
	        // Map 을 zoom 합니다. 
	        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
	        
	        // 마커 설정.
			MarkerOptions optFirst = new MarkerOptions();
			optFirst.position(latLng);// 위도 • 경도
			optFirst.title("Current Position");// 제목 미리보기
			optFirst.snippet("Snippet");
			optFirst.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
			mGoogleMap.addMarker(optFirst).showInfoWindow();
		}
	}
}

 

 

안드로이드(Android) 현재 GPS 정보를 알아와 구글맵에 마커 표시하기

반응형
Posted by 녹두장군1
,