演示Android百度地图操作功能

jopen 11年前

在本文中将演示百度地图的操作功能,包括缩放,旋转,视角切换,点击,双击,长按事件触发的操作以及截图等。百度地图本来就内置有缩放,旋转功能,那么在这里,截图(其实很多手机也自带截图功能)以及点击事件的监听算是比较有实际意义的功能。代码原型来源百度demo:

Activity:

package com.home;    import java.io.File;  import java.io.FileNotFoundException;  import java.io.FileOutputStream;  import java.io.IOException;    import com.baidu.mapapi.BMapManager;  import com.baidu.mapapi.map.MKMapTouchListener;  import com.baidu.mapapi.map.MKMapViewListener;  import com.baidu.mapapi.map.MapController;  import com.baidu.mapapi.map.MapPoi;  import com.baidu.mapapi.map.MapView;  import com.baidu.platform.comapi.basestruct.GeoPoint;    import android.app.Activity;  import android.graphics.Bitmap;  import android.os.Bundle;  import android.os.Environment;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;  import android.widget.EditText;  import android.widget.TextView;  import android.widget.Toast;    public class ControlBMapActivity extends Activity {   /**    * MapView 是地图主控件    */   private MapView mMapView = null;   /**    * 用MapController完成地图控制    */   private MapController mMapController = null;   /**    * MKMapViewListener 用于处理地图事件回调    */   MKMapViewListener mMapListener = null;   /**    * 用于截获屏坐标    */   MKMapTouchListener mapTouchListener = null;   /**    * 当前地点击点    */   private GeoPoint currentPt = null;   /**    * 控制按钮    */   private Button zoomButton = null;   private Button rotateButton = null;   private Button overlookButton = null;   private Button saveScreenButton = null;   private String touchType = null;   /**    * 用于显示地图状态的面板    */   private TextView mStateTextView = null;     @Override   protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    DemoApplication app = (DemoApplication) this.getApplication();    if (app.mBMapManager == null) {     app.mBMapManager = new BMapManager(this);     /**      * 如果BMapManager没有初始化则初始化BMapManager      */     app.mBMapManager.init(DemoApplication.strKey,       new DemoApplication.MyGeneralListener());    }    setContentView(R.layout.control_main);    mMapView = (MapView) findViewById(R.id.bmapView);    /**     * 获取地图控制器     */    mMapController = mMapView.getController();    /**     * 设置地图是否响应点击事件 .     */    mMapController.enableClick(true);    /**     * 设置地图缩放级别     */    mMapController.setZoom(12);      mStateTextView = (TextView) findViewById(R.id.state);    /**     * 初始化地图事件监听     */    initListener();    /**     * 将地图默认移动至天安门     */    double cLat = 39.945;    double cLon = 116.404;    GeoPoint p = new GeoPoint((int) (cLat * 1E6), (int) (cLon * 1E6));    mMapController.setCenter(p);   }     private void initListener() {    /**     * 设置地图点击事件监听     */    mapTouchListener = new MKMapTouchListener() {     @Override     public void onMapClick(GeoPoint point) {      touchType = "单击";      currentPt = point;      updateMapState();       }       @Override     public void onMapDoubleClick(GeoPoint point) {      touchType = "双击";      currentPt = point;      updateMapState();     }       @Override     public void onMapLongClick(GeoPoint point) {      touchType = "长按";      currentPt = point;      updateMapState();     }    };    mMapView.regMapTouchListner(mapTouchListener);    /**     * 设置地图事件监听     */    mMapListener = new MKMapViewListener() {     @Override     public void onMapMoveFinish() {      /**       * 在此处理地图移动完成回调 缩放,平移等操作完成后,此回调被触发       */      updateMapState();     }       @Override     public void onClickMapPoi(MapPoi mapPoiInfo) {      /**       * 在此处理底图poi点击事件 显示底图poi名称并移动至该点 设置过:       * mMapController.enableClick(true); 时,此回调才能被触发       *        */       }       @Override     public void onGetCurrentMap(Bitmap b) {      /**       * 当调用过 mMapView.getCurrentMap()后,此回调会被触发 可在此保存截图至存储设备       *        */      if (!Environment.MEDIA_MOUNTED.equals(Environment        .getExternalStorageState())) {       Toast.makeText(ControlBMapActivity.this, "请插入SD卡",         Toast.LENGTH_SHORT).show();       return;      }      File file = new File(Environment.getExternalStorageDirectory(),        System.currentTimeMillis() + ".png");      FileOutputStream out;      try {       out = new FileOutputStream(file);       if (b.compress(Bitmap.CompressFormat.PNG, 70, out)) {        out.flush();        out.close();       }       Toast.makeText(ControlBMapActivity.this,         "屏幕截图成功,图片存在: " + file.toString(),         Toast.LENGTH_SHORT).show();      } catch (FileNotFoundException e) {       e.printStackTrace();      } catch (IOException e) {       e.printStackTrace();      }       }       @Override     public void onMapAnimationFinish() {      /**       * 地图完成带动画的操作(如: animationTo())后,此回调被触发       */      updateMapState();     }       @Override     public void onMapLoadFinish() {     }    };    mMapView.regMapViewListener(DemoApplication.getInstance().mBMapManager,      mMapListener);    /**     * 设置按键监听     */    zoomButton = (Button) findViewById(R.id.zoombutton);    rotateButton = (Button) findViewById(R.id.rotatebutton);    overlookButton = (Button) findViewById(R.id.overlookbutton);    saveScreenButton = (Button) findViewById(R.id.savescreen);    OnClickListener onClickListener = new OnClickListener() {     @Override     public void onClick(View view) {      if (view.equals(zoomButton)) {       perfomZoom();      } else if (view.equals(rotateButton)) {       perfomRotate();      } else if (view.equals(overlookButton)) {       perfomOverlook();      } else if (view.equals(saveScreenButton)) {       // 截图,在MKMapViewListener中保存图片       mMapView.getCurrentMap();       Toast.makeText(ControlBMapActivity.this, "正在截取屏幕图片...",         Toast.LENGTH_SHORT).show();        }      updateMapState();     }      };    zoomButton.setOnClickListener(onClickListener);    rotateButton.setOnClickListener(onClickListener);    overlookButton.setOnClickListener(onClickListener);    saveScreenButton.setOnClickListener(onClickListener);   }     /**    * 处理缩放,sdk缩放级别范围:[3.0,19.0],小于3.0将按3.0处理;大于19.0将按19.0处理    */   private void perfomZoom() {    EditText t = (EditText) findViewById(R.id.zoomlevel);    try {     float zoomLevel = Float.parseFloat(t.getText().toString());     mMapController.setZoom(zoomLevel);    } catch (NumberFormatException e) {     Toast.makeText(this, "请输入正确的缩放级别,范围: [3.0,19.0],只能输入浮点型或整型",       Toast.LENGTH_SHORT).show();    }   }     /**    * 处理旋转 ,旋转角单位:度 ,逆时针旋转    */   private void perfomRotate() {    EditText t = (EditText) findViewById(R.id.rotateangle);    try {     int rotateAngle = Integer.parseInt(t.getText().toString());     mMapController.setRotation(rotateAngle);    } catch (NumberFormatException e) {     Toast.makeText(this, "请输入正确的旋转角度,只能为整型", Toast.LENGTH_SHORT).show();    }   }     /**    * 处理俯视 俯角范围: -45 ~ 0 , 单位: 度    */   private void perfomOverlook() {    EditText t = (EditText) findViewById(R.id.overlookangle);    try {     int overlookAngle = Integer.parseInt(t.getText().toString());     mMapController.setOverlooking(overlookAngle);    } catch (NumberFormatException e) {     Toast.makeText(this, "请输入正确的俯角,范围:  -45 ~ 0", Toast.LENGTH_SHORT)       .show();    }   }     /**    * 更新地图状态显示面板    */   private void updateMapState() {    if (mStateTextView == null) {     return;    }    String state = "";    if (currentPt == null) {     state = "点击、长按、双击地图以获取经纬度和地图状态";    } else {     state = String.format(touchType + ",当前经度 : %f 当前纬度:%f",       currentPt.getLongitudeE6() * 1E-6,       currentPt.getLatitudeE6() * 1E-6);    }    state += "\n";    state += String      .format("zoom level= %.1f    rotate angle= %d   overlaylook angle=  %d",        mMapView.getZoomLevel(), mMapView.getMapRotation(),        mMapView.getMapOverlooking());    mStateTextView.setText(state);   }     @Override   protected void onPause() {    /**     * MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause()     */    mMapView.onPause();    super.onPause();   }     @Override   protected void onResume() {    /**     * MapView的生命周期与Activity同步,当activity恢复时需调用MapView.onResume()     */    mMapView.onResume();    super.onResume();   }     @Override   protected void onDestroy() {    /**     * MapView的生命周期与Activity同步,当activity销毁时需调用MapView.destroy()     */    mMapView.destroy();    super.onDestroy();   }     @Override   protected void onSaveInstanceState(Bundle outState) {    super.onSaveInstanceState(outState);    mMapView.onSaveInstanceState(outState);     }     @Override   protected void onRestoreInstanceState(Bundle savedInstanceState) {    super.onRestoreInstanceState(savedInstanceState);    mMapView.onRestoreInstanceState(savedInstanceState);   }  }

布局XML:

<?xml version="1.0" encoding="utf-8"?>  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:orientation="vertical" >        <LinearLayout          android:id="@+id/layout_bottom"          android:layout_width="match_parent"          android:layout_height="50dip"          android:layout_alignParentBottom="true"          android:orientation="horizontal" >            <Button              android:id="@+id/zoombutton"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_weight="1"              android:text="缩放" />            <EditText              android:id="@+id/zoomlevel"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_weight="1"              android:text="10" />            <Button              android:id="@+id/rotatebutton"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_weight="1"              android:text="旋转" />            <EditText              android:id="@+id/rotateangle"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_weight="1"              android:numeric="integer"              android:text="90" />            <Button              android:id="@+id/overlookbutton"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_weight="1"              android:text="俯视" />            <EditText              android:id="@+id/overlookangle"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_weight="1"              android:text="-30" />      </LinearLayout>        <TextView          android:id="@+id/state"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:layout_above="@id/layout_bottom"          android:text="点击、长按、双击地图以获取经纬度和地图状态" />        <RelativeLayout          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:layout_above="@id/state"          android:orientation="vertical" >            <com.baidu.mapapi.map.MapView              android:id="@+id/bmapView"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:clickable="true" />            <Button              android:id="@+id/savescreen"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_alignParentRight="true"              android:layout_alignParentTop="true"              android:layout_marginTop="10dip"              android:text="截图" />      </RelativeLayout>    </RelativeLayout>

Application类及Manifest同上文。

附上图片效果:

演示Android百度地图操作功能