2012年4月12日 星期四

[Android]TrackMyPosition (定位、顯示地址、海拔高度、運動方向、速度)



    Mode : Street View

    Mode : Satellite View


功能描述
1. 可使用 GPS 衛星定位(GPS Provider)或無線網路定位(Network Provider)
2. 使用 GoogleMap 顯示即時所在位置
3. 顯示模式
 (a) 街道(Street View)
    (b) 衛星(Satellite View)
4. 顯示所在位置的地址
5. 顯示資訊:
    (a) Location Counts
    (b) Location Provider
    (c) 海拔高度 (Altitude)
    (d) 運動方向 (Bearing)
    (e) 速度(km/h) (Speed)


<TrackMyPosition.java>

   1: package com.android.trackmylocation;
   2:  
   3: import java.util.List;
   4: import java.util.Locale;
   5:  
   6: import com.google.android.maps.GeoPoint;
   7: import com.google.android.maps.MapActivity;
   8: import com.google.android.maps.MapController;
   9: import com.google.android.maps.MapView;
  10: import com.google.android.maps.MyLocationOverlay;
  11: import com.google.android.maps.Overlay;
  12:  
  13: import android.app.AlertDialog;
  14: import android.content.Context;
  15: import android.content.DialogInterface;
  16: import android.content.Intent;
  17: import android.location.Address;
  18: import android.location.Criteria;
  19: import android.location.Geocoder;
  20: import android.location.Location;
  21: import android.location.LocationListener;
  22: import android.location.LocationManager;
  23: import android.os.Bundle;
  24: import android.provider.Settings;
  25: import android.view.View;
  26: import android.view.View.OnClickListener;
  27: import android.view.WindowManager;
  28: import android.widget.Button;
  29: import android.widget.TextView;
  30: import android.widget.Toast;
  31:  
  32: public class TrackMyLocation extends MapActivity implements LocationListener {
  33:     private LocationManager locationManager;
  34:     private MapView mapView;
  35:     private MapController mapController;
  36:     private MyLocationOverlay mylayer;
  37:     private Button btnStreet, btnSatellite, btnExit;
  38:     private TextView tv00, tv01;
  39:     private int cnt;
  40:     private boolean enableTool;
  41:     private String strCnt, provider, providerFlag, altitude, bearing, speed;
  42:     private Criteria criteria = new Criteria();
  43:  
  44:     /** Called when the activity is first created. */
  45:     @Override
  46:     public void onCreate(Bundle savedInstanceState)
  47:     {
  48:         super.onCreate(savedInstanceState);
  49:         setContentView(R.layout.main);
  50:         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  51:         
  52:         findViews();
  53:         findControl();
  54:         setButtonListeners();
  55:     }
  56:  
  57:     private void init()
  58:     {
  59:         if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
  60:         {
  61:             new AlertDialog.Builder(TrackMyLocation.this).setTitle("地圖工具").setMessage("您尚未開啟定位服務,要前往設定頁面啟動定位服務嗎?")
  62:                     .setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener()
  63:                     {
  64:                         public void onClick(DialogInterface dialog, int which)
  65:                         {
  66:                             startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
  67:                         }
  68:                     }).setNegativeButton("Cancel", new DialogInterface.OnClickListener()
  69:                     {
  70:                         public void onClick(DialogInterface dialog, int which)
  71:                         {
  72:                             Toast.makeText(TrackMyLocation.this, "未開啟定位服務,無法使用本工具!!", Toast.LENGTH_SHORT).show();
  73:                         }
  74:                     }).show();
  75:         }
  76:         else
  77:         {
  78:             enableMyLocation();
  79:             enableTool = true;
  80:         }
  81:     }
  82:  
  83:     private void findViews(){
  84:         mapView = (MapView) findViewById(R.id.gmap);
  85:         btnStreet = (Button) findViewById(R.id.streetViewBtn);
  86:         btnSatellite = (Button) findViewById(R.id.satelliteViewBtn);
  87:         btnExit = (Button) findViewById(R.id.exitBtn);
  88:         tv00 = (TextView) findViewById(R.id.textView00);
  89:         tv01 = (TextView) findViewById(R.id.textView01);
  90:     }
  91:     
  92:     private void findControl()
  93:     {
  94:         mapView.setSatellite(false);
  95:         mapView.setBuiltInZoomControls(true);
  96:         mapController = mapView.getController();
  97:         mapController.setZoom(18);
  98:         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  99:         
 100:         criteria.setAccuracy(Criteria.ACCURACY_FINE);
 101:         criteria.setAltitudeRequired(true);
 102:         criteria.setBearingRequired(true);
 103:         criteria.setCostAllowed(false);
 104:         criteria.setSpeedRequired(true);
 105:         criteria.setPowerRequirement(Criteria.POWER_LOW);
 106:         locationManager.requestLocationUpdates(    LocationManager.GPS_PROVIDER,
 107:                                                 5000,
 108:                                                 0,
 109:                                                 TrackMyLocation.this);
 110:         locationManager.requestLocationUpdates(    LocationManager.NETWORK_PROVIDER,
 111:                                                 5000,
 112:                                                 0,
 113:                                                 TrackMyLocation.this);       
 114:     }
 115:  
 116:     private void setButtonListeners(){
 117:         btnStreet.setOnClickListener(new View.OnClickListener() {
 118:             public void onClick(View v) {
 119:                 mapView.setSatellite(false);
 120:             }
 121:          });
 122:   
 123:         btnSatellite.setOnClickListener(new View.OnClickListener() {
 124:             public void onClick(View v) {
 125:                 mapView.setSatellite(true);
 126:             }
 127:          });
 128:         
 129:         btnExit.setOnClickListener(new OnClickListener(){
 130:             public void onClick(View v) {
 131:                 android.os.Process.killProcess(android.os.Process.myPid());
 132:             }
 133:         });
 134:     }
 135:     
 136:     private void enableMyLocation()
 137:     {
 138:         List<Overlay> overlays = mapView.getOverlays();
 139:         mylayer = new MyLocationOverlay(this, mapView);
 140:         mylayer.enableCompass();
 141:         mylayer.enableMyLocation();
 142:         mylayer.runOnFirstFix(new Runnable()
 143:         {
 144:             public void run()
 145:             {
 146:                 mapController.animateTo(mylayer.getMyLocation());
 147:             }
 148:         });
 149:         overlays.add(mylayer);
 150:     }
 151:  
 152:     @Override
 153:     protected void onResume()
 154:     {
 155:         super.onResume();
 156:         if (enableTool)
 157:         {
 158:             locationManager.requestLocationUpdates(    LocationManager.GPS_PROVIDER,
 159:                                                     5000,
 160:                                                     0,
 161:                                                     TrackMyLocation.this);
 162:             locationManager.requestLocationUpdates(    LocationManager.NETWORK_PROVIDER,
 163:                                                     5000,
 164:                                                     0,
 165:                                                     TrackMyLocation.this);       
 166:  
 167:             mylayer.enableMyLocation();
 168:             mylayer.enableCompass();
 169:         }
 170:         else
 171:         {
 172:             init();
 173:         }
 174:     }
 175:  
 176:     @Override
 177:     protected void onPause()
 178:     {
 179:         super.onPause();
 180:         if (enableTool)
 181:         {
 182:             locationManager.removeUpdates(TrackMyLocation.this);
 183:             mylayer.disableCompass();
 184:             mylayer.disableMyLocation();
 185:         }
 186:     }
 187:  
 188:     @Override
 189:     protected boolean isRouteDisplayed()
 190:     {
 191:         return false;
 192:     }
 193:  
 194:     
 195:     public void onLocationChanged(Location location){
 196:         provider = locationManager.getBestProvider(criteria, true);
 197:         if ( provider.equals(String.valueOf("gps")))
 198:         {
 199:             providerFlag = "gps";
 200:         }
 201:         else
 202:         {
 203:             providerFlag = "network";    
 204:         }    
 205:         cnt = cnt + 1;
 206:         strCnt = String.valueOf(cnt);
 207:         tv00.setText(getAddressByLocation(location));
 208:         altitude = String.valueOf(location.getAltitude());
 209:         speed = String.valueOf(location.getSpeed()*3.6);
 210:         bearing = String.valueOf(location.getBearing());
 211:         tv01.setText(    "("+strCnt+")"+
 212:                         " 訊號:"+providerFlag+
 213:                         " 海拔:"+altitude+
 214:                         " 方向:"+bearing+
 215:                         " 時速:"+speed);
 216:         GeoPoint p = new GeoPoint(    (int) (location.getLatitude() * 1000000),
 217:                                     (int) (location.getLongitude() * 1000000));
 218:         mapController.animateTo(p);
 219:     } 
 220:  
 221:     public void onProviderDisabled(String provider)
 222:     {
 223:  
 224:     }
 225:  
 226:     public void onProviderEnabled(String provider)
 227:     {
 228:  
 229:     }
 230:  
 231:     public void onStatusChanged(String provider, int status, Bundle extras)
 232:     {
 233:  
 234:     }
 235:     
 236:     public String getAddressByLocation(Location location) {
 237:         String returnAddress = "";
 238:         try {
 239:             if (location != null) {
 240:                     Double longitude = location.getLongitude();
 241:                     Double latitude = location.getLatitude();
 242:                     Geocoder gc = new Geocoder(this, Locale.TRADITIONAL_CHINESE);
 243:                     List<Address> lstAddress = gc.getFromLocation(latitude, longitude, 1);
 244:                     returnAddress = lstAddress.get(0).getAddressLine(0);
 245:             }
 246:         }
 247:         catch(Exception e) {
 248:             e.printStackTrace();
 249:         }
 250:         
 251:         return returnAddress;
 252:     }
 253:  }


<main.xml>

   1: <?xml version="1.0" encoding="utf-8"?>

   2: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

   3:     android:layout_width="fill_parent"

   4:     android:layout_height="fill_parent"

   5:     android:orientation="vertical" >

   6:  

   7:     <TextView

   8:         android:id="@+id/textView00"

   9:         android:layout_width="fill_parent"

  10:         android:layout_height="wrap_content"

  11:         android:text="@string/strNull" />

  12:     

  13:         <com.google.android.maps.MapView

  14:                 android:id="@+id/gmap"

  15:                 android:layout_width="fill_parent"

  16:                 android:layout_height="fill_parent"

  17:                 android:apiKey="自行申請一組 apiKey"

  18:                 android:layout_weight="1"

  19:                 android:clickable="true"    />

  20:          

  21:         <LinearLayout 

  22:             android:orientation="horizontal"

  23:             android:layout_width="fill_parent"

  24:             android:layout_height="wrap_content"

  25:             android:layout_weight="0">

  26:  

  27:         <Button

  28:             android:id="@+id/streetViewBtn"

  29:             android:layout_width="wrap_content"

  30:             android:layout_height="wrap_content"

  31:             android:text="@string/strStreet" />

  32:  

  33:         <Button

  34:             android:id="@+id/satelliteViewBtn"

  35:             android:layout_width="wrap_content"

  36:             android:layout_height="wrap_content"

  37:             android:text="@string/strSatellite" />

  38:  

  39:         <Button

  40:             android:id="@+id/exitBtn"

  41:             android:layout_width="wrap_content"

  42:             android:layout_height="wrap_content"

  43:             android:text="@string/strExit" />

  44:  

  45:  

  46:         <TextView

  47:             android:id="@+id/textView01"

  48:             android:layout_width="wrap_content"

  49:             android:layout_height="wrap_content"

  50:             android:text="@string/strNull" />

  51:  

  52:     </LinearLayout>

  53:  

  54: </LinearLayout>


<strings.xml>

   1: <?xml version="1.0" encoding="utf-8"?>

   2: <resources>

   3:  

   4:     <string name="hello">Hello World, TrackMyLocation!</string>

   5:     <string name="app_name">定位追蹤</string>

   6:     <string name="strStreet">街道</string>

   7:     <string name="strSatellite">衛星</string>

   8:     <string name="strExit">離開</string>

   9:     <string name="strNull"></string>

  10:  

  11: </resources>


<AndroidManifest.xml>

   1: <?xml version="1.0" encoding="utf-8"?>

   2: <manifest xmlns:android="http://schemas.android.com/apk/res/android"

   3:     package="com.android.trackmylocation"

   4:     android:versionCode="1"

   5:     android:versionName="1.0" >

   6:  

   7:     <uses-sdk android:minSdkVersion="7" />

   8:     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

   9:     <uses-permission android:name="android.permission.INTERNET"/>

  10:     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

  11:  

  12:     <application

  13:         android:icon="@drawable/gps"

  14:         android:label="@string/app_name" >

  15:         <activity

  16:             android:name=".TrackMyLocation"

  17:             android:label="@string/app_name" >

  18:             <intent-filter>

  19:                 <action android:name="android.intent.action.MAIN" />

  20:  

  21:                 <category android:name="android.intent.category.LAUNCHER" />

  22:             </intent-filter>

  23:         </activity>

  24:         <uses-library android:name="com.google.android.maps"/>

  25:     </application>

  26:  

  27: </manifest>

沒有留言:

張貼留言