百度安卓地圖學習(三)

來源:互聯網
上載者:User

讀完後http://blog.csdn.net/woshishuoshuoa/article/details/9858417,接著看看這篇博文吧,這篇文章是將前倆篇的搜尋和定位進行了簡單地整合,並在點擊搜尋到的標誌處可以簡單地顯示所在位置的名稱。註:這裡的給出的代碼都是在之前的項目上新增的哦~~~

建立linemap.xml檔案:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <LinearLayout      android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="horizontal" >    <EditText         android:id="@+id/edit_linemap"         android:layout_width="wrap_content"         android:layout_height="match_parent"         android:layout_weight="1" />    <Button         android:id="@+id/btn1_linemap"        android:text="搜尋"         android:layout_width="wrap_content"         android:layout_height="match_parent"/>     <Button          android:id="@+id/btn2_linemap"         android:text="定位"         android:layout_width="wrap_content"         android:layout_height="match_parent"/></LinearLayout><LinearLayout     android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="horizontal"     >    <RadioButton        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="鹽城"       android:id="@+id/radio1"        />    <RadioButton         android:layout_width="match_parent"        android:layout_height="wrap_content"         android:text="上海"       android:id="@+id/radio2"        />    <RadioButton         android:layout_width="match_parent"       android:layout_height="wrap_content"        android:text="南京"       android:id="@+id/radio3"        /></LinearLayout><com.baidu.mapapi.map.MapView android:id="@+id/linemap_bmapsView"                      android:layout_width="fill_parent"                      android:layout_height="fill_parent"                      android:clickable="true" />  </LinearLayout>

建立pop_window_text.xml檔案:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:background="@drawable/popup" >    <TextView         android:id="@+id/tv_pop_window_item"        android:layout_width="wrap_content"        android:layout_height="39px"        android:text="Text"        android:textSize="16dp"        android:gravity="center"        android:background="#383838"        android:textColor="#fff"        /></LinearLayout>

建立activity代碼如下:

package com.diecolor;import com.baidu.location.BDLocation;import com.baidu.location.BDLocationListener;import com.baidu.location.LocationClient;import com.baidu.location.LocationClientOption;import com.baidu.mapapi.BMapManager;import com.baidu.mapapi.map.LocationData;import com.baidu.mapapi.map.MKEvent;import com.baidu.mapapi.map.MapController;import com.baidu.mapapi.map.MapView;import com.baidu.mapapi.map.MyLocationOverlay;import com.baidu.mapapi.map.PoiOverlay;import com.baidu.mapapi.map.PopupClickListener;import com.baidu.mapapi.map.PopupOverlay;import com.baidu.mapapi.map.TransitOverlay;import com.baidu.mapapi.search.MKAddrInfo;import com.baidu.mapapi.search.MKBusLineResult;import com.baidu.mapapi.search.MKDrivingRouteResult;import com.baidu.mapapi.search.MKPlanNode;import com.baidu.mapapi.search.MKPoiInfo;import com.baidu.mapapi.search.MKPoiResult;import com.baidu.mapapi.search.MKSearch;import com.baidu.mapapi.search.MKSearchListener;import com.baidu.mapapi.search.MKShareUrlResult;import com.baidu.mapapi.search.MKSuggestionResult;import com.baidu.mapapi.search.MKTransitRouteResult;import com.baidu.mapapi.search.MKWalkingRouteResult;import com.baidu.platform.comapi.basestruct.GeoPoint;import android.app.Activity;import android.app.ProgressDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.View.MeasureSpec;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.RadioButton;import android.widget.TextView;import android.widget.Toast;public class LineMapActivity extends Activity{GeoPoint geoPoint;Button btn1,btn2;    EditText editText;    RadioButton radioButton1,radioButton2,radioButton3;     BMapManager mBMapMan = null;      MapView mMapView = null;    MKSearch mkSearch=null;    String city;    Handler handler;    ProgressDialog progressDialogCity;      PoiOverlay poiOverlay;//興趣點圖層    MyLocationOverlay myLocationOverlay;//定位元影像層     public LocationClient mLocationClient=null;    public BDLocationListener myListener=new MyLocationListener();@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);mBMapMan=new BMapManager(getApplication());  mBMapMan.init("4b605b48b3062e4687d0ada2ecd65a8e", null);    //注意:請在試用setContentView前初始化BMapManager對象,否則會報錯  setContentView(R.layout.linemap_main);  mMapView=(MapView)findViewById(R.id.linemap_bmapsView);  btn1=(Button) findViewById(R.id.btn1_linemap);btn2=(Button) findViewById(R.id.btn2_linemap);radioButton1=(RadioButton) findViewById(R.id.radio1);radioButton2=(RadioButton) findViewById(R.id.radio2);radioButton3=(RadioButton) findViewById(R.id.radio3);editText=(EditText) findViewById(R.id.edit_linemap);mMapView.setBuiltInZoomControls(true);  MapController mapController=mMapView.getController();//得到mMapView控制權,可以用它控制盒驅動平移和縮放GeoPoint point=new GeoPoint((int)(39.915* 1E6),(int)(116.404* 1E6));//用給定的經緯度構造一個GeoPoint,單位是微度 (度 * 1E6)mapController.setCenter(point);//設定地圖中心點mapController.setZoom(12);//設定地圖zoom層級 //初始化 查詢mkSearch=new MKSearch();mkSearch.init(mBMapMan, new MySearchListener());//注意,MKSearchListener只支援一個,以最後一次設定為準  mLocationClient=new LocationClient(getApplicationContext());//聲明LocationClient類mLocationClient.registerLocationListener(myListener);//註冊監聽函數mMapView.getController().enableClick(true);//否則不會調用mklistnerLocationClientOption option=new LocationClientOption();option.setOpenGps(true);option.setAddrType("all");//返回的定位結果包含地址資訊option.setCoorType("bd0911");//返回的定位結果是百度經緯度,預設值gcj02option.setScanSpan(LocationClientOption.MIN_SCAN_SPAN);//設定發起定位請求的間隔時間為5000msoption.disableCache(true);//禁止啟用緩衝定位option.setPoiDistance(1000);//poi查詢距離option.setPoiExtraInfo(true);//是否需要POI的電話和地址等詳細資料mLocationClient.setLocOption(option);        btn2.setOnClickListener(new OnClickListener() {       @Overridepublic void onClick(View v) {// TODO Auto-generated method stubmLocationClient.start();mMapView.getController().setZoom(15);if (mLocationClient!=null&&mLocationClient.isStarted()) {mLocationClient.requestLocation();}else {Log.d("LocSDK3", "location is null or not started");//興趣點if (mLocationClient!=null&&mLocationClient.isStarted()) {mLocationClient.requestPoi();}}}});//初次定位if (mLocationClient != null && mLocationClient.isStarted())mLocationClient.requestLocation();else Log.d("LocSDK3", "locClient is null or not started");//興趣點if (mLocationClient != null && mLocationClient.isStarted())mLocationClient.requestPoi();btn1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//得到當前的地理資訊GeoPoint centerPoint=mMapView.getMapCenter();mkSearch.reverseGeocode(centerPoint);//得到城市//非同步處理progressDialogCity=new ProgressDialog(LineMapActivity.this);progressDialogCity.setCancelable(true);progressDialogCity.setTitle("查詢--"+editText.getText().toString());progressDialogCity.setMessage("正在查詢,請稍候.............");progressDialogCity.show();}});handler=new Handler(){@Overridepublic void handleMessage(Message msg) {if (msg.what==0x001) {progressDialogCity.dismiss();//消失if (city==null||city.equals("")) {Toast.makeText(LineMapActivity.this, "城市資訊擷取失敗",3000).show();return;}mkSearch.poiSearchInCity(city, editText.getText().toString());}}};//添加listener//mMapView.regMapViewListener(mBMapMan, new MapViewListener());}class MyLocationListener implements BDLocationListener{@Overridepublic void onReceiveLocation(BDLocation location) {// TODO Auto-generated method stubGeoPoint geoPoint=new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));/* MyLocationOverlay只負責顯示我的位置,, * 將擷取的位置資料放在一個LocationData結構中並用該結構設定MyLcationOverlay的資料來源, * 即可建立MyLocationOverlay。*/MyLocationOverlay myLocationOverlay=new MyLocationOverlay(mMapView);LocationData locationData=new LocationData();//將擷取的位置資料放在一個LocationData結構中locationData.latitude=location.getLatitude();locationData.longitude=location.getLongitude();locationData.direction=2.0f;myLocationOverlay.setData(locationData);//設定MyLcationOverlay的資料來源mMapView.getOverlays().clear();mMapView.getOverlays().add(myLocationOverlay);if (poiOverlay!=null) {mMapView.getOverlays().add(poiOverlay);}mMapView.refresh();//在更新地圖覆蓋物後,需調用MapView.refresh() 使更新生效mMapView.getController().animateTo(geoPoint);}@Overridepublic void onReceivePoi(BDLocation arg0) {// TODO Auto-generated method stub}}public class MySearchListener implements MKSearchListener{/*reverseGeocode和geocode的返回結果在都在MKSearchListener裡的onGetAddrResult方法中, * 具體區分是逆位址解析的結果還是位址解析的結果需要判斷MKAddrInfo中的type欄位,type欄位為MKAddrInfo.MK_GEOCODE的是地理編碼的結果、type欄位為MKAddrInfo.MK_REVERSEGEOCODE的是逆地理編碼的結果*/@Overridepublic void onGetAddrResult(MKAddrInfo res, int error) {// TODO Auto-generated method stubif (error != 0) {          String str = String.format("錯誤號碼:%d", error);          Toast.makeText(LineMapActivity.this, str, Toast.LENGTH_LONG).show();          return;      }     //地圖移動到該點     // mMapView.getController().animateTo(res.geoPt);      if (res.type == MKAddrInfo.MK_GEOCODE) {          //地理編碼:通過地址檢索座標點          String strInfo = String.format("緯度:%f 經度:%f", res.geoPt.getLatitudeE6()/1e6, res.geoPt.getLongitudeE6()/1e6);          Toast.makeText(LineMapActivity.this, strInfo, Toast.LENGTH_LONG).show();      }      if (res.type == MKAddrInfo.MK_REVERSEGEOCODE) {          //反地理編碼:通過座標點檢索詳細地址及周邊poi          city=  res.addressComponents.city;          Toast.makeText(LineMapActivity.this, city, Toast.LENGTH_LONG).show();      }      //查詢完成發訊息    Message message=new Message();    message.what=0x001;    handler.sendMessage(message);}@Overridepublic void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {// TODO Auto-generated method stub}@Overridepublic void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {// TODO Auto-generated method stub}@Overridepublic void onGetPoiDetailSearchResult(int arg0, int arg1) {// TODO Auto-generated method stubif (arg1 != 0) {Toast.makeText(LineMapActivity.this, "抱歉,未找到結果",Toast.LENGTH_SHORT).show();} else {Toast.makeText(LineMapActivity.this, "成功,查看詳情頁面",Toast.LENGTH_SHORT).show();}}public void onGetPoiResult(MKPoiResult res, int type, int error) {// TODO Auto-generated method stub// 錯誤號碼可參考MKEvent中的定義  if ( error == MKEvent.ERROR_RESULT_NOT_FOUND){    Toast.makeText(LineMapActivity.this, "抱歉,未找到結果",Toast.LENGTH_LONG).show();      return ;          }          else if (error != 0 || res == null) {   Toast.makeText(LineMapActivity.this, "搜尋出錯啦..", Toast.LENGTH_LONG).show();  return;        }// 將poi結果顯示到地圖上  PlacePoiOverlay poiOverlay = new PlacePoiOverlay(LineMapActivity.this, mMapView);  poiOverlay.setData(res.getAllPoi());  //把查詢結果 放置到層中mMapView.getOverlays().clear();  //清空以前查詢的結果mMapView.getOverlays().add(poiOverlay); //添加搜尋結果的層 mMapView.refresh();  //重新整理//當ePoiType為2(公交線路)或4(地鐵線路)時, poi座標為空白  for (MKPoiInfo mk : res.getAllPoi()) {if (mk.pt!=null) {mMapView.getController().animateTo(mk.pt);break;}}}@Overridepublic void onGetShareUrlResult(MKShareUrlResult arg0, int arg1, int arg2) {// TODO Auto-generated method stub}@Overridepublic void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {// TODO Auto-generated method stub}@Overridepublic void onGetTransitRouteResult(MKTransitRouteResult result, int error) {// TODO Auto-generated method stubif (error!=0) {Toast.makeText(LineMapActivity.this, "沒有公交線路!", 3000).show();return;}if (result==null) {Toast.makeText(LineMapActivity.this, "沒有公交線路!", 3000).show();return;}TransitOverlay transitOverlay=new TransitOverlay(LineMapActivity.this, mMapView);transitOverlay.setData(result.getPlan(0));mMapView.getOverlays().clear();if (myLocationOverlay!=null) {mMapView.getOverlays().add(myLocationOverlay);}if (poiOverlay!=null) {mMapView.getOverlays().add(poiOverlay);}mMapView.getOverlays().add(transitOverlay);mMapView.refresh();}@Overridepublic void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {// TODO Auto-generated method stub}}//class MapViewListener implements MKMapViewListener{////@Override//public void onClickMapPoi(MapPoi poi) {//// TODO Auto-generated method stub////map poi//GeoPoint geoPoint=poi.geoPt;//String description=poi.strText;////PopupOverlay popupOverlay=new PopupOverlay(mMapView, new PopupClickListener() {////@Override//public void onClickedPopup(int arg0) {//// TODO Auto-generated method stub////}//});//Bitmap[] bitmaps=new Bitmap[3];//try {//bitmaps[0]=BitmapFactory.decodeStream(getAssets().open("marker1.png"));//bitmaps[1]=BitmapFactory.decodeStream(getAssets().open("marker2.png"));//bitmaps[2]=BitmapFactory.decodeStream(getAssets().open("marker3.png"));//} catch (Exception e) {//e.printStackTrace();//}//popupOverlay.showPopup(bitmaps, geoPoint, 32);////mMapView.getController().animateTo(geoPoint);//}////@Override//public void onGetCurrentMap(Bitmap arg0) {//// TODO Auto-generated method stub////}////@Override//public void onMapAnimationFinish() {//// TODO Auto-generated method stub////}////@Override//public void onMapLoadFinish() {//// TODO Auto-generated method stub////}////@Override//public void onMapMoveFinish() {//// TODO Auto-generated method stub////}}//自訂 興趣點層public class PlacePoiOverlay extends PoiOverlay {MKSearch mSearch;public PlacePoiOverlay(Activity activity, MapView mapView) {super(activity, mapView);}//單擊氣球 快顯視窗@Overrideprotected boolean onTap(int i) {super.onTap(i);finalMKPoiInfo mkPoiInfo = getPoi(i);PopupOverlay popupOverlay = new PopupOverlay(mMapView,new PopupClickListener() {@Overridepublic void onClickedPopup(int arg0) {// TODO Auto-generated method stubif (geoPoint==null) {Toast.makeText(LineMapActivity.this, "自我定位失敗", 2000).show();return;}MKPlanNode start=new MKPlanNode();start.pt=geoPoint;MKPlanNode end=new MKPlanNode();end.pt=mkPoiInfo.pt;mkSearch.transitSearch(city, start, end);}});Bitmap[] bitmaps = new Bitmap[3];try {bitmaps[0] = BitmapFactory.decodeStream(getAssets().open("marker1.png"));// //////////////把XML檔案轉換成圖片View popview = LayoutInflater.from(LineMapActivity.this).inflate(R.layout.pop_window_text, null);// 擷取要轉換的View資源TextView TestText = (TextView) popview.findViewById(R.id.tv_pop_window_item);TestText.setText(mkPoiInfo.name);// 將每個點的Title在彈窗中以文本形式顯示出來Bitmap popbitmap = convertViewToBitmap(popview);bitmaps[1] = popbitmap;bitmaps[2] = BitmapFactory.decodeStream(getAssets().open("marker3.png"));} catch (Exception e) {e.printStackTrace();}popupOverlay.showPopup(bitmaps, mkPoiInfo.pt, 32);mMapView.getController().animateTo(mkPoiInfo.pt);return true;}}@Override  protected void onDestroy(){          mMapView.destroy();          if(mBMapMan!=null){                  mBMapMan.destroy();                  mBMapMan=null;          }          super.onDestroy();  }  @Override  protected void onPause(){          mMapView.onPause();          if(mBMapMan!=null){                 mBMapMan.stop();          }          super.onPause();  }  @Override  protected void onResume(){          mMapView.onResume();          if(mBMapMan!=null){                  mBMapMan.start();          }         super.onResume();  }  /////////輔助方法// 把xml檔案轉換成圖片public Bitmap convertViewToBitmap(View view) {view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());view.buildDrawingCache();Bitmap bitmap = view.getDrawingCache();return bitmap;}}

本文的例子比較小,存在一些小錯誤,還有待完善。。。不過會持續更新的哦~~~歡迎喜歡安卓的親們提出你們的寶貴意見哦~~~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.