[Android算法] android定位和地图开发实例

来源:互联网 发布:检测手机硬件的软件 编辑:程序博客网 时间:2024/05/17 06:58
在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 :MapViewGPS坐标与设备坐标的转换(GeoPointPoint)。

定位系统包中的主要类:

LocationManager:本类提供访问定位服务的功能,也提供获取最佳定位提供者的功能。另外,临近警报功能也可以借助该类来实现。
LocationProvider:该类是定位提供者的抽象类。定位提供者具备周期性报告设备地理位置的功能。
LocationListener:提供定位信息发生改变时的回调功能。必须事先在定位管理器中注册监听器对象。
Criteria:该类使得应用能够通过在LocationProvider中设置的属性来选择合适的定位提供者。
Geocoder:用于处理地理编码和反向地理编码的类。地理编码是指将地址或其他描述转变为经度和纬度,反向地理编码则是将经度和纬度转变为地址或描述语言,其中包含了两个构造函数,需要传入经度和纬度的坐标。getFromLocation方法可以得到一组关于地址的数组。

下面开始地图定位实例的开发,在开发地图前需要 获取Android 地图 API 密钥 网上有很多资料,这里就不再复述。

首先要在manifest.xml中设置全相应的权限和maps库:

  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:

  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>
复制代码
下面是核心代码,重要的地方我做了注释:

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

可以放大缩小:
0_1328753416gvUt.gif 

可是使用menu键,切换不同的模式:
0_1328753569NsOt.gif 

上面是切换到了卫星模式。由于地图需要耗费大量的网络资源,如果网络比较慢的话会等待很长时间。

转自:http://blog.csdn.net/wangkuifeng0118/article/details/7244364
原创粉丝点击