안드로이드에서 구글Map을 불러오고, GPS좌표를 표현하는 방식
- 안드로이드 버젼 : 2.x
1. MapActivity만들기
- 안드로이드 버젼 : 2.x
1. MapActivity만들기
public class Map2 extends MapActivity { //--------------------- /** Called when the activity is first created. */ //--------------------- @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } private void initVar() { textView.setText("시작="); // 상단 텍스트 영역 textView2.setText("시작=..."); // 하단 텍스트 영역 lat=0.0d; // latitude lng=0.0d; // longitude acc=""; // 정확도 pro=""; // 좌표 정보 제공자 gps_status="2"; addressString = "..."; fine=0; // 0 : GPS 1: Network } }2. main.xml 수정 ( ui.png ) -l (지도 apiKey는 구글 발급 사이트를 통해서 ) – 화면 구성 입니다. // 개인 pc key값에 의해 MapKey가 만들어 집니다.
3.OnCreate() 설정 -– 텍스트 출력 창 설정 / 버튼 설정 [ GPS 로그 보기는 제외 합니다. ]
//--------------------- /** Called when the activity is first created. */ //--------------------- @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mContext = this; //--------------------- // 텍스트 : 현재위치 주소 //--------------------- linearLayout = (LinearLayout) findViewById(R.id.textview); textView = new TextView(this); textView.setTextColor(Color.BLUE); textView.setGravity(Gravity.CENTER); //textView.setText(addressString); linearLayout.addView(textView); //--------------------- // 텍스트 : 상태 정보 //--------------------- linearLayout2 = (LinearLayout) findViewById(R.id.textview2); textView2 = new TextView(this); textView2.setTextColor(Color.BLUE); textView2.setGravity(Gravity.BOTTOM); linearLayout2.addView(textView2); //--------------------- // 지도 불러오기 //--------------------- initMap(); //--------------------- // 재시작 버튼 //--------------------- btnUpdate = (Button)findViewById(R.id.Button01); //----------------------------------- // GPS 좌표 얻기 //--------------------- btnUpdate.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub runGPS(); // GPS 가동 시키기 } }); //--------------------- // 재시작 버튼 //--------------------- btnList = (Button)findViewById(R.id.Button02); //----------------------------------- // GPS 좌표 얻기 //--------------------- btnList.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub // GPS 로그를 서버에 보내고 받아서 보는 모듈을 각자 구현해 주세요. //Intent i = new Intent(mContext,GpsLog.class); //startActivity(i); } }); }4. 지도 초기 설정 - 지도 불러 오기
//--------------------- // 지도 불러오기 //--------------------- private void initMap() { mapView = (MapView) findViewById(R.id.mapview); mc = (MapController)mapView.getController(); // 아래 두개로 확대/축소 버튼 생성 mapView.setBuiltInZoomControls(true); mapView.displayZoomControls(true); //지도 레벨 설정 max:21 / satellite :18 mc.setZoom(20); //mc.setZoom(7); // 한국지도 레벨 //mc.setZoom(13); // 광역시 정도 레벨 }5. GPS 작동 시키기, 좌표 받기 - 시작 버튼 클릭
public void runGPS() { btnUpdate.setEnabled(false); this.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub initVar(); // 화면 갱신 하기 위한 값들 } }); // 위치 매니저 locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if ( !locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { } else { //--------------------- //1. GPS 시작 //--------------------- registerLocationListeners(); // 위치 수신자들 가동.. //_send2Svr() ; // chkTimeOut(); // 특정 시간내에 응답없으면 강제 마무리 하게 하기 위해 /// 특히 실내에서.. btnUpdate.setEnabled(true); } }5-1.
private void createLocationListeners() { // network를 통해 들어오는 좌표 listenerCoarse = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extras) { switch ( status ) { case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: locationAvailable = false; case LocationProvider.AVAILABLE: locationAvailable = true; } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onLocationChanged(Location newLocation) { currentLocation = newLocation; if ( newLocation.getAccuracy()>1000 && newLocation.hasAccuracy()) { //--------------------- //위치 매니저 제거 listenerCoarse //--------------------- locManager.removeUpdates(this); } //--------------------- //1-1-1 위치 확인 : 현재위치 주소 가져오기 //--------------------- updateGps(currentLocation,0); textView.setText("감지1COARSE [정확도:"+acc+"][provider:"+pro+"]"); } }; listenerFine = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extras) { switch ( status ) { case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: locationAvailable = false; case LocationProvider.AVAILABLE: locationAvailable = true; } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onLocationChanged(Location newLocation) { currentLocation = newLocation; if ( newLocation.getAccuracy()>1000 && newLocation.hasAccuracy()) { //--------------------- //위치 매니저 제거 listenerFine //--------------------- locManager.removeUpdates(this); } //--------------------- //1-1-1 위치 확인 : 현재위치 주소 가져오기 //--------------------- updateGps(currentLocation,0); textView.setText("감지2FINE [정확도: "+ acc+"][provider:"+pro+"]"); } }; }5-2.
private void chkTimeOut() { Handler handler = new Handler(); handler.postDelayed( new Runnable() { @Override public void run() { if ( lat == 0.0d ) { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); String provider = locManager.getBestProvider(criteria, true); Location location = locManager.getLastKnownLocation(provider); if ( location != null ) updateGps(location,1); String oldString4 = textView2.getText().toString(); textView2.setText(oldString4+"LastKnown방식 [정확도:"+acc+"] [provider:" +pro+"]"); } //--------------------- //위치 매니저 제거 //--------------------- removeListener(); } }, 15*1000 ); // 15 seconds }5-3.
public void removeListener() { locManager.removeUpdates(listenerCoarse); locManager.removeUpdates(listenerFine); } private void updateGps(Location location, int type) { // type = 0 : listener : 위치 수신자 // type = 1 : LastKnown : 최종 정보 if( fine == 1 ) return; // GPS에 갱신이 된 상태이면… 굳이 Network 변경정보를 안받게 다는 것임 if ( type == 0 ) { // type = 0 : listener : 위치 수신자 if ( location.getProvider().equals("gps")) { gps_status="0"; fine=1; } else if (location.getProvider().equals("network")) { gps_status="1"; } } else { // type = 1 : LastKnown : 최종 정보 by chkTimeOut() gps_status="2"; } lat = location.getLatitude(); // Latitude lng = location.getLongitude(); // Longitude int accInt = (int)location.getAccuracy(); acc = Integer.toString(accInt); // 위치 정확도 pro = location.getProvider(); // 위치 제공자 updateAddress(location); // 주소 갱신 createAndShowCustomOverlay(location); // 지도 다시 그리기 }5-4.
//--------------------- //--------------------- //1-1-1 : 현재 위치 지도 이동 //--------------------- protected void createAndShowCustomOverlay(Location newLocation) { List overlays = mapView.getOverlays(); // first remove old overlay if (overlays.size() > 0) { for (Iterator iterator = overlays.iterator(); iterator.hasNext();) { iterator.next(); iterator.remove(); } } // transform the location to a geopoint GeoPoint geopoint = new GeoPoint((int)(newLocation.getLatitude() * 1E6), (int)(newLocation.getLongitude() * 1E6)); // Create new Overlay MyOverlay overlay = new MyOverlay(geopoint); mapView.getOverlays().add(overlay); mapView.setSatellite(false); // 위성지도 // move to location mapView.getController().animateTo(geopoint); } //--------------------- //1-1-1 위치 확인 : 현재위치 주소 가져와서 변경 //--------------------- private void updateAddress(Location location) { String add = ""; // GeoCoder : 경도 위도 좌표로 주소 얻기 Geocoder gc = new Geocoder(mapView.getContext(), Locale.getDefault()); try { // 주소 가져오기 List < Address > addresses = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1); if (addresses.size() > 0) { for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex() + 1; i++) { add += addresses.get(0).getAddressLine(i); } } } catch (IOException e) { e.printStackTrace(); } StringTokenizer st = new StringTokenizer(add); int i = 0; while (st.hasMoreTokens()) { addressArray[i++] = st.nextToken(); } textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setTextColor(Color.BLUE); String oldString3 = textView.getText().toString(); if (addressArray[0] == null) { textView.setText(oldString3 + ddressString); } else { // 주소 : 시 군 구 textView.setText(oldString3 + addressArray[1] + " " + addressArray[2] + " " + addressArray[3] + " " + addressArray[4]); } }5-5.
public class MyOverlay extends Overlay { int INFO_WINDOW_WIDTH = 240; // 150; //125; int INFO_WINDOW_HEIGHT = 28; // 25; private GeoPoint geopoint = null; public MyOverlay(GeoPoint point) { geopoint = point; } public void draw(Canvas canvas, MapView mapView, boolean shadow) { // Transfrom geoposition to Point on canvas Projection projection = mapView.getProjection(); Point point = new Point(); projection.toPixels(geopoint, point); //---add the marker--- Bitmap userBmp = BitmapFactory.decodeResource(mapView.getResources(), R.drawable.bubble); canvas.drawBitmap(userBmp, point.x, point.y, null); // 박스 RectF infoWindowRect = new RectF(0, 0, INFO_WINDOW_WIDTH, // “여기”.length()*14, 문자열 길이로 하거나 INFO_WINDOW_HEIGHT); // 지도 상대 좌표 int infoWindowOffsetX = point.x; //-INFO_WINDOW_WIDTH/2; int infoWindowOffsetY = point.y; //-INFO_WINDOW_HEIGHT; // -bubbleIcon.getHeight(); infoWindowRect.offset(infoWindowOffsetX, infoWindowOffsetY); // Draw inner info window canvas.drawRoundRect(infoWindowRect, 5, 5, getInnerPaint()); // Draw border for info window canvas.drawRoundRect(infoWindowRect, 5, 5, getBorderPaint()); // Draw the MapLocation's name //int TEXT_OFFSET_X = 10; //int TEXT_OFFSET_Y = 15; canvas.drawText(“여기”, // 표현할 글자 infoWindowOffsetX + TEXT_OFFSET_X, infoWindowOffsetY + TEXT_OFFSET_Y, getTextPaint()); } public Paint getInnerPaint() { if (innerPaint == null) { innerPaint = new Paint(); innerPaint.setARGB(225, 75, 75, 75); //gray innerPaint.setAntiAlias(true); } return innerPaint; } public Paint getBorderPaint() { if (borderPaint == null) { borderPaint = new Paint(); borderPaint.setARGB(255, 255, 255, 255); borderPaint.setAntiAlias(true); borderPaint.setStyle(Style.STROKE); borderPaint.setStrokeWidth(2); } return borderPaint; } public Paint getTextPaint() { if (textPaint == null) { textPaint = new Paint(); textPaint.setARGB(255, 255, 255, 255); textPaint.setAntiAlias(true); textPaint.setTextSize(18); textPaint.setTypeface(Typeface.DEFAULT_BOLD); } return textPaint; } }
'0.일반개발' 카테고리의 다른 글
Visual Studio 2010 프로젝트 속성 페이지 (0) | 2015.12.03 |
---|---|
$LogFile ( NTFS 볼륨 로그 ) (0) | 2015.12.01 |
Eclipse Workingset (0) | 2015.11.18 |
IBM BlueMix (0) | 2015.11.17 |
호스트(Windows)에서 게스트(Linux)로 ssh 접속하기 (0) | 2015.11.13 |