출처 : http://www.shop-wiz.com/document/android/google_map_example1

[설명]
- GPS를 이용한 내위치값 받기
DDMS > Emulator Control > Location Controls > Manual(원하는 좌표값 입력후 "Send")
manifest xml : <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 확인
이번에도 먼저 전체 소스를 보여 드리겠습니다.
[설명]
AndroidManifest.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8"?>
      package="com.ProjectMyPosition"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ProjectMyPosition"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="com.google.android.maps" />
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>   
    
[설명]
res/layout/main.xml
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="your apikey here"
/>       
    
[설명]
res/values/strings.xml
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<resources
    <string name="hello">Hello World, ProjectMyPosition!</string>
    <string name="app_name">ProjectMyPosition</string>
    <string name="Location_fail_title">데이터 오류</string>
    <string name="Location_fail_message">현재 위치 정보를 얻어올 수 없습니다. GPS를 ON하셨는지 확인바랍니다.</string>
</resources>
          
    
[설명]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.ProjectMyPosition;
  
import android.os.Bundle;
  
import com.google.android.maps.MapActivity;
  
    public class ProjectMyPosition 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() {
            return false;
        }   
    }   
    
[설명]
ProjectMyPosition.java
너무 길어서 압박감이 느껴지시나요?
이전 장에서 다룬것에서 몇가지가 추가 되었습니다.
추가된 내용중 핵심은 loadGps() 에 있는
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
입니다. location을 구하기 위해 provider를 구하는 것입니다.
물론 location은
이전장에 GeoPoint point = new GeoPoint((int)(37.5643406*1E6),(int)(126.9756087*1E6));
대신에 eoPoint point = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6)); 처럼 능동적으로 하기 위해서입니다.

나머지는 에러 처리 구문이라고 보시면됩니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package com.ProjectMyPosition;
  
import java.util.List;
  
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
  
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
    public class ProjectMyPosition extends MapActivity {
        private static final String TAG = ProjectMyPosition.class.toString();
        private static boolean result = false;
          
        private LocationManager locationManager;
        private String provider;
        private Location location;
          
        private MapView mapView;
        private MapController mapController;
          
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState){
             super.onCreate(savedInstanceState); 
             setContentView(R.layout.main);
               
             //xml에 apiKey정의가 없을 경우 MapView mapview = new MapView(context, "your api key");처럼 사용가능
            mapView = (MapView) findViewById(R.id.mapview);
            mapView.setBuiltInZoomControls(true);  
  
  
         
            // load GPS( GPS 로 부터 현재의 내 위치값 가져오기 )
            loadGps();//location 값 할당
              
            List<Overlay> mapOverlays = mapView.getOverlays();
            Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
            MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable,this);
              
            //GeoPoint  point = new GeoPoint((int)(37.5643406*1E6),(int)(126.9756087*1E6));
            GeoPoint  point = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));
            OverlayItem overlayitem = new OverlayItem(point, "Hi Pondol!", "I'm in Seoul!");
            itemizedoverlay.addOverlay(overlayitem);
     
            mapController = mapView.getController();
            mapController.setCenter(point);
            mapController.setZoom(15);
           // mapController.animateTo( point );
            mapOverlays.add(itemizedoverlay);
              
              
        }
          
        @Override
        protected boolean isRouteDisplayed() {
            return false;
        }   
  
          
        public void loadGps() {
            Log.w(TAG , "loadGps Start" );
              
            String context = Context.LOCATION_SERVICE;//안드로이드 시스템으로 부터 LocationManager 서비스를 요청하여 할당
            locationManager = (LocationManager)getSystemService(context);
             
            //GPS 환경설정
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);       // 정확도
            criteria.setPowerRequirement(Criteria.POWER_LOW);   // 전원 소비량
            criteria.setAltitudeRequired(false);                // 고도, 높이 값을 얻어 올지를 결정
            criteria.setBearingRequired(false);                 // provider 기본 정보
            criteria.setSpeedRequired(false);                   //속도
            criteria.setCostAllowed(true);                      //위치 정보를 얻어 오는데 들어가는 금전적 비용
              
            //상기 조건을 이용하여 알맞은 GPS선택후 위치정보를 획득
              
            //manifest xml  : <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />//로케이션 메니저의 provider 
            provider = locationManager.getBestProvider(criteria, true);
            Log.i(TAG, "provider:"+provider);
            if(provider == null){//GPS 장치가 없는 휴대폰이거나 설정이 꺼져있는 경우 바로 alert 처리하거나 GPS 설정으로 이동
                result = chkGpsService();
                if(result){
                    loadGps();
                }
                  
            }else{
                location = locationManager.getLastKnownLocation(provider);//가장 최근의 로케이션을 가져온다. 안드로이드 폰이 꺼져있었거나 다른 위치로 이동한 경우 값이 없다.
                //location = locationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER );
                //이럴경우는 NETWORK_PROVIDER 로 부터 새로운 location을 지정 받는다.
                //특정조건(시간, 거리)이 되면  Listener를 invoke 시킨다.: 여기서는 1초 마다 5km)
                locationManager.requestLocationUpdates(provider, 1000, 5, loclistener);//현재정보를 업데이트
                  
                if(location == null){
                    location = locationManager.getLastKnownLocation(provider);
                    if(location == null){//그래도 null인경우 alert;
                        Log.w(TAG, "get Location From GPS Fail !!!!!");
                        AlertDialog.Builder adb = new AlertDialog.Builder(ProjectMyPosition.this);
                        adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                        adb.setTitle( R.string.Location_fail_title );
                        adb.setMessage(R.string.Location_fail_message);
                        adb.show();
                    }
  
                }
            }
        }   
          
        private final LocationListener loclistener = new LocationListener(){
            public void onLocationChanged(Location location) {
                Log.w(TAG , "onLocationChanged" );
            }
  
            public void onProviderDisabled(String provider) {
                Log.w(TAG , "onProviderDisabled" );
            }
  
            public void onProviderEnabled(String provider) {
                Log.w(TAG , "onProviderEnabled" );
            }
  
            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.w(TAG , "onStatusChanged" );
            
        };
          
        private boolean chkGpsService() {//GPS의 설정여부 확인 및 자동 설정 변경
            String gs = android.provider.Settings.Secure.getString(getContentResolver(),
            android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            Log.w("chkGpsService" , "get GPs Service" );
              
            if (gs.indexOf("gps", 0) < 0) {
                Log.w("chkGpsService" , "status: off" );
                // GPS OFF 일때 Dialog 띄워서 설정 화면으로 이동.
                AlertDialog.Builder gsDialog = new AlertDialog.Builder(this);
                gsDialog.setTitle("GPS Status OFF !!!");
                gsDialog.setMessage("Change Setting !!");
                gsDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // GPS설정 화면으로 이동
                        Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        startActivity(intent);
                    }
                }).create().show();
                return false;
            } else {
                Log.w("chkGpsService" , "status: on" );                 
                return true;
            }
        }     
  
    }
        
[설명]
MyItemizedOverlay.java
기존의 구글 맵 뷰에서 설명한 것과 동일 하므로 별다른 설명은 없습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.ProjectMyPosition;
  
import java.util.ArrayList;
  
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
  
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
  
public class MyItemizedOverlay extends ItemizedOverlay {
  
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    private Context mContext;
       
    // constructor 
    public MyItemizedOverlay(Drawable defaultMarker, Context context) {
        super(boundCenterBottom(defaultMarker));
        mContext = context;
    }
       
    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }
       
    @Override
    protected OverlayItem createItem(int i) {
      return mOverlays.get(i);
    }
   
    @Override
    public int size() {
        return mOverlays.size();
    }
       
    @Override
    protected boolean onTap(int index) {
      OverlayItem item = mOverlays.get(index);
      AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
      dialog.setTitle(item.getTitle());
      dialog.setMessage(item.getSnippet());
      dialog.show();
      return true;
    }   
   
   
}   

+ Recent posts