移動百度地圖常用功能全集

程序運行效果圖

功能有:顯示地圖、顯示當前位置、路線規劃、地圖縮放、衛星視圖

詳細功能代碼:

package com.yidin.map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPlanNode;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.baidu.mapapi.RouteOverlay;
import com.baidu.mapapi.TransitOverlay;
import com.yidin.mylocation.R;
public class RoutePlan extends MapActivity {
    private LocationListener mLocationListener = null;// create時註冊此listener,Destroy時需要Remove
    private Button mBtnDrive = null; // 駕車搜索
    private Button mBtnTransit = null; // 公交搜索
    private Button mBtnWalk = null; // 步行搜索
    private MapView mMapView = null; // 地圖View
    private MKSearch mSearch = null; // 搜索模塊,也可去掉地圖模塊獨立使用
    private BMapApiDemoApp app;
    private MyLocationOverlay mLocationOverlay = null; // 我的位置
    private LinearLayout localLayout, routeLayout;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.routeplan);
        localLayout = (LinearLayout) findViewById(R.id.local);
        routeLayout = (LinearLayout) findViewById(R.id.route);
        app = (BMapApiDemoApp) this.getApplication();
        if (app.mBMapMan == null) {
            app.mBMapMan = new BMapManager(getApplication());
            app.mBMapMan.init(app.mStrKey,
                    new BMapApiDemoApp.MyGeneralListener());
        }
        app.mBMapMan.start();
        // 如果使用地圖SDK,請初始化地圖Activity
        super.initMapActivity(app.mBMapMan);
        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.setBuiltInZoomControls(true);
        // 設置在縮放動畫過程中也顯示overlay,默認爲不繪製
        mMapView.setDrawOverlayWhenZooming(true);
        // 初始化搜索模塊,註冊事件監聽
        mSearch = new MKSearch();
        mSearch.init(app.mBMapMan, new MKSearchListener() {
            public void onGetPoiDetailSearchResult(int type, int error) {
            }
            public void onGetDrivingRouteResult(MKDrivingRouteResult res,
                    int error) {
                // 錯誤號可參考MKEvent中的定義
                if (error != 0 || res == null) {
                    Toast.makeText(RoutePlan.this, "抱歉,未找到結果",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                RouteOverlay routeOverlay = new RouteOverlay(RoutePlan.this,
                        mMapView);
                // 此處僅展示一個方案作爲示例
                routeOverlay.setData(res.getPlan(0).getRoute(0));
                mMapView.getOverlays().clear();
                mMapView.getOverlays().add(routeOverlay);
                mMapView.invalidate();
                mMapView.getController().animateTo(res.getStart().pt);
            }
            public void onGetTransitRouteResult(MKTransitRouteResult res,
                    int error) {
                if (error != 0 || res == null) {
                    Toast.makeText(RoutePlan.this, "抱歉,未找到結果",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                TransitOverlay routeOverlay = new TransitOverlay(
                        RoutePlan.this, mMapView);
                // 此處僅展示一個方案作爲示例
                routeOverlay.setData(res.getPlan(0));
                mMapView.getOverlays().clear();
                mMapView.getOverlays().add(routeOverlay);
                mMapView.invalidate();
                mMapView.getController().animateTo(res.getStart().pt);
            }
            public void onGetWalkingRouteResult(MKWalkingRouteResult res,
                    int error) {
                if (error != 0 || res == null) {
                    Toast.makeText(RoutePlan.this, "抱歉,未找到結果",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                RouteOverlay routeOverlay = new RouteOverlay(RoutePlan.this,
                        mMapView);
                // 此處僅展示一個方案作爲示例
                routeOverlay.setData(res.getPlan(0).getRoute(0));
                mMapView.getOverlays().clear();
                mMapView.getOverlays().add(routeOverlay);
                mMapView.invalidate();
                mMapView.getController().animateTo(res.getStart().pt);
            }
            public void onGetAddrResult(MKAddrInfo res, int error) {
            }
            public void onGetPoiResult(MKPoiResult res, int arg1, int arg2) {
            }
            public void onGetBusDetailResult(MKBusLineResult result, int iError) {
            }
            @Override
            public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
                // TODO Auto-generated method stub
            }
            public void onGetRGCShareUrlResult(String arg0, int arg1) {
                // TODO Auto-generated method stub
            }
        });
        // 設定搜索按鈕的響應
        mBtnDrive = (Button) findViewById(R.id.drive);
        mBtnTransit = (Button) findViewById(R.id.transit);
        mBtnWalk = (Button) findViewById(R.id.walk);
        OnClickListener clickListener = new OnClickListener() {
            public void onClick(View v) {
                SearchButtonProcess(v);
            }
        };
        mBtnDrive.setOnClickListener(clickListener);
        mBtnTransit.setOnClickListener(clickListener);
        mBtnWalk.setOnClickListener(clickListener);
        // 添加定位圖層
        mLocationOverlay = new MyLocationOverlay(this, mMapView);
        mMapView.getOverlays().add(mLocationOverlay);
        // 註冊定位事件
        mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if (location != null) {
                    String strLog = String.format("您當前的位置:\r\n" + "經度:%f\r\n"
                            + "緯度:%f", location.getLongitude(),
                            location.getLatitude());
                    TextView mainText = (TextView) findViewById(R.id.textview);
                    mainText.setText(strLog);
                    GeoPoint pt = new GeoPoint(
                            (int) (location.getLatitude() * 1e6),
                            (int) (location.getLongitude() * 1e6));
                    mMapView.getController().animateTo(pt);//移動地圖將此點作爲中心移動
                }
            }
        };
            
        ((ToggleButton) findViewById(R.id.toggleButton1)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked){//衛星視圖
                    mMapView.setSatellite(false);
                }else{
                    mMapView.setSatellite(true);
                }
            }
        });
    }
    void SearchButtonProcess(View v) {
        // 處理搜索按鈕響應
        EditText editSt = (EditText) findViewById(R.id.start);
        EditText editEn = (EditText) findViewById(R.id.end);
        // 對起點終點的name進行賦值,也可以直接對座標賦值,賦值座標則將根據座標進行搜索
        MKPlanNode stNode = new MKPlanNode();
        stNode.name = editSt.getText().toString();
        MKPlanNode enNode = new MKPlanNode();
        enNode.name = editEn.getText().toString();
        // 實際使用中請對起點終點城市進行正確的設定
        if (mBtnDrive.equals(v)) {
            mSearch.drivingSearch("北京", stNode, "上海", enNode);
        } else if (mBtnTransit.equals(v)) {
            mSearch.transitSearch("北京", stNode, enNode);
        } else if (mBtnWalk.equals(v)) {
            mSearch.walkingSearch("北京", stNode, "北京", enNode);
        }
    }
    @Override
    protected void onPause() {
        app.mBMapMan.stop();
        super.onPause();
    }
    @Override
    protected void onResume() {
        // BMapApiDemoApp app = (BMapApiDemoApp) this.getApplication();
        app.mBMapMan.start();
        super.onResume();
    }
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, Menu.FIRST + 3, 1003, "自我定位").setIcon(
        android.R.drawable.ic_menu_edit);
        menu.add(Menu.NONE, Menu.FIRST + 4, 1004, "路徑規劃").setIcon(
        android.R.drawable.ic_menu_delete);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case Menu.FIRST + 3:
            // 註冊Listener
            app.mBMapMan.getLocationManager().requestLocationUpdates(
                    mLocationListener);
            mLocationOverlay.enableMyLocation();
            localLayout.setVisibility(View.VISIBLE);
            break;
        case Menu.FIRST + 4:
            routeLayout.setVisibility(View.VISIBLE);
            break;
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        // 移除listener
        app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
        mLocationOverlay.disableMyLocation();
        super.onDestroy();
    }
        
    /**
     * 多個overlay顯示時通過ItemizedOverlay
     *
     * @author cola
     *
     */
    class MyOverItem extends ItemizedOverlay<OverlayItem> {
        private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();
        private Drawable marker;
        private RoutePlan mContext;
        protected HashMap<String, ImageView> isSelected;
        private int layout_x = 0; // 用於設置popview 相對某個位置向x軸偏移
        private int layout_y = -25; // 用於設置popview 相對某個位置向x軸偏移
//      public List<NearbyFriendsEntry> earbyFriendsList;
        public MyOverItem(Drawable marker, RoutePlan context) {
            super(boundCenterBottom(marker));
            this.marker = marker;
            this.mContext = (RoutePlan) context;
            this.layout_x = this.marker.getBounds().centerX();
            this.layout_y = -this.marker.getBounds().height();
//          this.earbyFriendsList = this.mContext.l;
            this.isSelected = new HashMap<String, ImageView>();
//          int size = this.earbyFriendsList.size();
//          for (int n = 0; n < size; n++) {
//              if (this.earbyFriendsList.get(n).WeiDu.equals("null"))
//                  continue;
//              double d = Double
//                      .parseDouble(this.earbyFriendsList.get(n).WeiDu);
//              GeoList.add(new OverlayItem(
//                      new GeoPoint((int) (d * 1E6),
//                              (int) (Double.parseDouble(this.earbyFriendsList
//                                      .get(n).JingDu) * 1E6)),
//                      this.earbyFriendsList.get(n).MemberName,
//                      this.earbyFriendsList.get(n).AccountId));
//          }
            populate();
        }
        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            // Projection接口用於屏幕像素點座標系統和地球表面經緯度點座標系統之間的變換
            Projection projection = mapView.getProjection();
//          int len = size() - 1;
//          for (int index = len; index >= 0; index--) { // 遍歷GeoList
//              OverlayItem overLayItem = getItem(index); // 得到給定索引的item
//              // String title = overLayItem.getTitle();
//              // // 把經緯度變換到相對於MapView左上角的屏幕像素座標
//              Point point = projection.toPixels(overLayItem.getPoint(), null);
//              final ImageView v;
//              NearbyFriendsEntry me = earbyFriendsList.get(index);
//              View tv = mContext.showTextArray.get(index);
//              ImageView iv = this.isSelected.get(me.AccountId);
//              if (iv == null) {
//                  v = (ImageView) tv.findViewById(R.id.iv);
//                  this.isSelected.put(me.AccountId, v);
//                  // } else
//                  // v = iv;
//                  Bitmap bm = null;
//
//                  if (me.PhotoUrl != null) {// 請求圖標
//                      bm = new NetImageBase().getLogoBitmap(handler,
//                              activity, me.PhotoUrl, new imageCallback() {
//                                  public void getImage(Bitmap bm) {
//                                      // TODO Auto-generated method stub
//                                      if (bm != null) {
//                                          v.setImageBitmap(bm);
//                                      }
//                                  }
//                              });
//                      if (bm != null) {
//                          v.setImageBitmap(bm);
//                      }
//                  }
//              }
//              MapView.LayoutParams geoLP = (MapView.LayoutParams) tv
//                      .getLayoutParams();
//              geoLP.x = point.x;// Y軸偏移
//              geoLP.y = point.y;// + 30;// Y軸偏移
//              tv.setVisibility(View.VISIBLE);
//              mapView.updateViewLayout(tv, geoLP);
//          }
            super.draw(canvas, mapView, shadow);
            // 調整一個drawable邊界,使得(0,0)是這個drawable底部最後一行中心的一個像素
            boundCenterBottom(marker);
        }
        @Override
        protected OverlayItem createItem(int i) {
            return GeoList.get(i);
        }
        @Override
        public int size() {
            return GeoList.size();
        }
        @Override
        /**
         * 處理當點擊事件
         * mapview的onTouch事件會傳播到overlay的 onTouch方法 通過點擊範圍可以確定觸發哪個overlay的onTap
         */
        protected boolean onTap(int i) {
            return true;
        }
        /**
         * 顯示相關的點
         */
        public void showOverlayItem(int n) {
            this.onTap(n);
        }
    }
}

更多的移動互聯網的發展趨勢app開發移動互聯網應用相關的資料請到互聯網的一點事www.yidin.net 留言

android QQ羣:222392467

資料:

http://www.yidin.net/?p=8280

http://www.yidin.net/?p=9725


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章