歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android定位和地圖開發實例

Android定位和地圖開發實例

日期:2017/3/1 10:33:38   编辑:Linux編程
在Android開發中地圖和定位是很多軟件不可或缺的內容,這些特色功能也給人們帶來了很多方便。

首先介紹一下地圖包中的主要類:

MapController : 主要控制地圖移動,伸縮,以某個GPS坐標為中心,控制MapView中的view組件,管理Overlay,提供View的基本功能。使用多種地圖模式(地圖模式(某些城市可實時對交通狀況進行更新),衛星模式,街景模式)來查看Google Map。常用方法:animateTo(GeoPoint point) setCenter(GeoPoint point) setZoom(int zoomLevel) 等。

Mapview : 是用來顯示地圖的view, 它派生自android.view.ViewGroup。當MapView獲得焦點,可以控制地圖的移動和縮放。地圖可以以不同的形式來顯示出來,如街景模式,衛星模式等,通過setSatellite(boolean) setTraffic(boolean), setStreetView(boolean) 方法。

Overlay : 是覆蓋到MapView的最上層,可以擴展其ondraw接口,自定義在MapView中顯示一些自己的東西。MapView通過MapView.getOverlays()對Overlay進行管理。

Projection :MapView中GPS坐標與設備坐標的轉換(GeoPoint和Point)。

定位系統包中的主要類:

LocationManager:本類提供訪問定位服務的功能,也提供獲取最佳定位提供者的功能。另外,臨近警報功能也可以借助該類來實現。

LocationProvider:該類是定位提供者的抽象類。定位提供者具備周期性報告設備地理位置的功能。

LocationListener:提供定位信息發生改變時的回調功能。必須事先在定位管理器中注冊監聽器對象。

Criteria:該類使得應用能夠通過在LocationProvider中設置的屬性來選擇合適的定位提供者。

Geocoder:用於處理地理編碼和反向地理編碼的類。地理編碼是指將地址或其他描述轉變為經度和緯度,反向地理編碼則是將經度和緯度轉變為地址或描述語言,其中包含了兩個構造函數,需要傳入經度和緯度的坐標。getFromLocation方法可以得到一組關於地址的數組。

下面開始地圖定位實例的開發,在開發地圖前需要 獲取Android 地圖 API 密鑰 網上有很多資料,這裡就不再復述。

首先要在manifest.xml中設置全相應的權限和maps庫:

[html]

  1. <application
  2. android:icon="@drawable/ic_launcher"
  3. android:label="@string/app_name" >
  4. <activity
  5. android:label="@string/app_name"
  6. android:name=".MyMapActivity" >
  7. <intent-filter >
  8. <action android:name="android.intent.action.MAIN" />
  9. <category android:name="android.intent.category.LAUNCHER" />
  10. </intent-filter>
  11. </activity>
  12. <span style="color:#FF6666;">
  13. <uses-library android:name="com.google.android.maps" /></span>
  14. </application>
  15. <span style="color:#FF6666;"> <uses-permission android:name="android.permission.INTERNET" />
  16. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  17. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /></span>
在上面我標紅的千萬不要忘記。

layout下的main.xml:

[html]

  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. <com.google.android.maps.MapView
  7. android:id="@+id/mapview"
  8. android:layout_width="fill_parent"
  9. android:layout_height="fill_parent"
  10. android:apiKey="008uu0x2a7GWlK2LzCW872afBAPLhJ-U2R26Wgw"
  11. />
  12. </LinearLayout>
下面是核心代碼,重要的地方我做了注釋:

[html]

  1. public class MyMapActivity extends MapActivity {
  2. /** Called when the activity is first created. */
  3. private MapController mapController;
  4. private MapView mapView;
  5. private MyOverLay myOverLay;
  6. @Override
  7. public void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.main);
  10. LocationManager locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
  11. mapView=(MapView) this.findViewById(R.id.mapview);
  12. //設置交通模式
  13. mapView.setTraffic(true);
  14. //設置衛星模式
  15. mapView.setSatellite(false);
  16. //設置街景模式
  17. mapView.setStreetView(false);
  18. //設置縮放控制
  19. mapView.setBuiltInZoomControls(true);
  20. mapView.setClickable(true);
  21. mapView.setEnabled(true);
  22. //得到MapController實例
  23. mapController=mapView.getController();
  24. mapController.setZoom(15);
  25. myOverLay=new MyOverLay();
  26. List<Overlay> overLays=mapView.getOverlays();
  27. overLays.add(myOverLay);
  28. Criteria criteria=new Criteria();
  29. criteria.setAccuracy(Criteria.ACCURACY_FINE);
  30. criteria.setAltitudeRequired(false);
  31. criteria.setBearingRequired(false);
  32. criteria.setCostAllowed(false);
  33. criteria.setPowerRequirement(Criteria.POWER_LOW);
  34. //取得效果最好的Criteria
  35. String provider=locationManager.getBestProvider(criteria, true);
  36. //得到Location
  37. Location location=locationManager.getLastKnownLocation(provider);
  38. updateWithLocation(location);
  39. //注冊一個周期性的更新,3秒一次
  40. locationManager.requestLocationUpdates(provider, 3000, 0, locationListener);
  41. }
  42. @Override
  43. public boolean onCreateOptionsMenu(Menu menu) {
  44. // TODO Auto-generated method stub
  45. menu.add(0, 1, 1, "交通模式");
  46. menu.add(0,2,2,"衛星模式");
  47. menu.add(0,3,3,"街景模式");
  48. return super.onCreateOptionsMenu(menu);
  49. }
  50. @Override
  51. public boolean onOptionsItemSelected(MenuItem item) {
  52. // TODO Auto-generated method stub
  53. super.onOptionsItemSelected(item);
  54. switch (item.getItemId()) {
  55. case 1://交通模式
  56. mapView.setTraffic(true);
  57. mapView.setSatellite(false);
  58. mapView.setStreetView(false);
  59. break;
  60. case 2://衛星模式
  61. mapView.setSatellite(true);
  62. mapView.setStreetView(false);
  63. mapView.setTraffic(false);
  64. break;
  65. case 3://街景模式
  66. mapView.setStreetView(true);
  67. mapView.setTraffic(false);
  68. mapView.setSatellite(false);
  69. break;
  70. default:
  71. mapView.setTraffic(true);
  72. mapView.setSatellite(false);
  73. mapView.setStreetView(false);
  74. break;
  75. }
  76. return true;
  77. }
  78. private void updateWithLocation(Location location){
  79. if(location!=null){
  80. //為繪制類設置坐標
  81. myOverLay.setLocation(location);
  82. GeoPoint geoPoint=new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6));
  83. //定位到指定的坐標
  84. mapController.animateTo(geoPoint);
  85. mapController.setZoom(15);
  86. }
  87. }
  88. private final LocationListener locationListener=new LocationListener() {
  89. @Override
  90. public void onStatusChanged(String provider, int status, Bundle extras) {
  91. // TODO Auto-generated method stub
  92. }
  93. @Override
  94. public void onProviderEnabled(String provider) {
  95. // TODO Auto-generated method stub
  96. }
  97. @Override
  98. public void onProviderDisabled(String provider) {
  99. // TODO Auto-generated method stub
  100. }
  101. //當坐標改變時出發此函數
  102. @Override
  103. public void onLocationChanged(Location location) {
  104. // TODO Auto-generated method stub
  105. updateWithLocation(location);
  106. }
  107. };
  108. class MyOverLay extends Overlay{
  109. private Location location;
  110. public void setLocation(Location location){
  111. this.location=location;
  112. }
  113. @Override
  114. public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
  115. long when) {
  116. // TODO Auto-generated method stub
  117. super.draw(canvas, mapView, shadow);
  118. Paint paint=new Paint();
  119. Point myScreen=new Point();
  120. //將經緯度換成實際屏幕的坐標。
  121. GeoPoint geoPoint=new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6));
  122. mapView.getProjection().toPixels(geoPoint, myScreen);
  123. paint.setStrokeWidth(1);
  124. paint.setARGB(255, 255, 0, 0);
  125. paint.setStyle(Paint.Style.STROKE);
  126. Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.mypicture);
  127. //把這張圖片畫到相應的位置。
  128. canvas.drawBitmap(bmp, myScreen.x, myScreen.y,paint);
  129. canvas.drawText("天堂沒有路", myScreen.x, myScreen.y, paint);
  130. return true;
  131. }
  132. }
  133. @Override
  134. protected boolean isRouteDisplayed() {
  135. // TODO Auto-generated method stub
  136. return false;
  137. }
  138. @Override
  139. public boolean onKeyDown(int keyCode, KeyEvent event) {
  140. // TODO Auto-generated method stub
  141. if (keyCode == KeyEvent.KEYCODE_BACK) {
  142. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  143. builder.setMessage("你確定退出嗎?")
  144. .setCancelable(false)
  145. .setPositiveButton("確定",
  146. new DialogInterface.OnClickListener() {
  147. public void onClick(DialogInterface dialog,
  148. int id) {
  149. MyMapActivity.this.finish();
  150. android.os.Process
  151. .killProcess(android.os.Process
  152. .myPid());
  153. android.os.Process.killProcess(android.os.Process.myTid());
  154. android.os.Process.killProcess(android.os.Process.myUid());
  155. }
  156. })
  157. .setNegativeButton("返回",
  158. new DialogInterface.OnClickListener() {
  159. public void onClick(DialogInterface dialog,
  160. int id) {
  161. dialog.cancel();
  162. }
  163. });
  164. AlertDialog alert = builder.create();
  165. alert.show();
  166. return true;
  167. }
  168. return super.onKeyDown(keyCode, event);
  169. }
  170. }
接下來看一下運行後效果:

可以放大縮小:

可是使用menu鍵,切換不同的模式:

上面是切換到了衛星模式。由於地圖需要耗費大量的網絡資源,如果網絡比較慢的話會等待很長時間。

Copyright © Linux教程網 All Rights Reserved