Android加载百度地图
生活随笔
收集整理的這篇文章主要介紹了
Android加载百度地图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ? ? ??
1、第一步:項目中添加lib文件夾,放入百度相關jar包,如下圖
第二步:編寫布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@drawable/back"android:orientation="vertical" ><FrameLayoutandroid:layout_width="fill_parent"android:layout_height="0dip"android:layout_weight="1"android:background="#FFFF00" ><LinearLayoutandroid:id="@+id/yqxx_table_title"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#FFFF00"android:orientation="vertical" ><WebViewandroid:id="@+id/webview"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@drawable/back" /></LinearLayout><com.baidu.mapapi.map.MapViewandroid:id="@+id/bmapView"android:layout_width="fill_parent"android:layout_height="fill_parent"android:clickable="true" /></FrameLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="55dp"android:orientation="horizontal" ><Buttonandroid:id="@+id/yqxx_List_Button"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="@drawable/yq_list_up" /><Buttonandroid:id="@+id/yqxx_Map_Button"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="@drawable/yq_map_down" /></LinearLayout></LinearLayout>
第三步:編寫Acvity程序
package cn.superyouth.www;import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import cn.superyouth.www.itools.ExitApp; import cn.superyouth.www.itools.xmTools;import com.baidu.mapapi.BMapManager; import com.baidu.mapapi.MKGeneralListener; import com.baidu.mapapi.map.ItemizedOverlay; 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.mapapi.map.OverlayItem; import com.baidu.mapapi.map.Symbol; import com.baidu.mapapi.map.TextItem; import com.baidu.mapapi.map.TextOverlay; import com.baidu.platform.comapi.basestruct.GeoPoint;import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast;public class SYIT_SSJC extends Activity implements MKGeneralListener {private LinearLayout yqxxTableTitle = null;private BMapManager mapManager = null; // 百度地圖控制器private MapView mMapView = null; // MapView 是地圖主控件private MapController mMapController = null;// 用MapController完成地圖控制private WebView webview = null;private Toast mToast;boolean isError = false;List<Map<String,Object>> curData = new ArrayList<Map<String, Object>>(5); // 當前頁面使用數據protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);ExitApp.getInstance().addActivity(this);mapManager = new BMapManager(getApplication());mapManager.init("8965CE898810FCFFB38B07079D4B7208658A4F7C", null);setContentView(R.layout.syit_ssjc);webview = (WebView) findViewById(R.id.webview);WebSettings webSettings = webview.getSettings();// 設置WebView屬性,能夠執行Javascript腳本webSettings.setJavaScriptEnabled(true);// 設置可以訪問文件webSettings.setAllowFileAccess(true);// 設置支持縮放webSettings.setBuiltInZoomControls(true);// 加載需要顯示的網頁// webview.loadUrl("http://192.168.0.121/CityLowerRoadSys/PDA/SQ_List.aspx");webview.loadUrl("http://61.190.32.10/CityLowerRoadSys/PDA/SQ_List.aspx");// 設置Web視圖webview.setWebViewClient(new webViewClient());TextView titleText = (TextView) findViewById(R.id.bar_title_backTitle);titleText.setText("實時監測");// 按鈕返回Button btnBack = (Button) findViewById(R.id.bar_title_backButton);btnBack.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {finish();}});// 設置列表和地圖按鈕---------------------------------------------------------------------final Button ListButton = (Button) findViewById(R.id.yqxx_List_Button);final Button MapButton = (Button) findViewById(R.id.yqxx_Map_Button);// UI// 列表layout層----------------------------------------------------------------------yqxxTableTitle = (LinearLayout) findViewById(R.id.yqxx_table_title);// 列表按鈕事件---------------------------------------------------------------------------ListButton.setOnClickListener(new ImageView.OnClickListener() {public void onClick(View v) {// 隱藏地圖、顯示列表// 并設置按鈕圖片的狀態----------------------------------------------yqxxTableTitle.setVisibility(View.VISIBLE);mMapView.setVisibility(View.GONE);ListButton.setBackgroundResource(R.drawable.yq_list_down);MapButton.setBackgroundResource(R.drawable.yq_map_up);}});// 地圖按鈕事件----------------------------------------------------------------------------MapButton.setOnClickListener(new ImageView.OnClickListener() {public void onClick(View v) {// 隱藏列表、顯示地圖// 并設置按鈕圖片的狀態-----------------------------------------------yqxxTableTitle.setVisibility(View.GONE);mMapView.setVisibility(View.VISIBLE);ListButton.setBackgroundResource(R.drawable.yq_list_up);MapButton.setBackgroundResource(R.drawable.yq_map_down);}});// -------------設置地圖的初始化和綁定----------------------------------------------mMapView = (MapView) findViewById(R.id.bmapView);mMapController = mMapView.getController(); // * 獲取地圖控制器mMapController.enableClick(true); //* 設置地圖是否響應點擊事件 .mMapController.setZoom(12); // * 設置地圖縮放級別mMapView.setBuiltInZoomControls(true); // * 顯示內置縮放控件mMapView.setTraffic(true); //設置顯示為衛星地圖:// 開啟線程new Thread() {@Overridepublic void run() {try {} catch (Exception e) {isError = true;System.out.println(e.toString());}handler.sendEmptyMessage(0); }}.start();}/*** 用Handler來更新UI*/private Handler handler = new Handler() {public void handleMessage(Message msg) {if(isError){//創建提示Dialog alertDialog = new AlertDialog.Builder(SYIT_SSJC.this). setTitle("提示"). setMessage("服務器無響應,請稍候再試!"). setIcon(R.drawable.ic_launcher). create(); alertDialog.show();}else{new ReadHttpGet().execute("http://61.190.32.10/CityLowerRoadSys/ashx/ssjc.ashx");}}};// * 顯示Toast消息private void showToast(String msg) {if (mToast == null) {mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);} else {mToast.setText(msg);mToast.setDuration(Toast.LENGTH_SHORT);}mToast.show();}// Web視圖private class webViewClient extends WebViewClient {public boolean shouldOverrideUrlLoading(WebView view, String url) {view.loadUrl(url);return true;}}@Overrideprotected void onPause() {// MapView的生命周期與Activity同步,當activity掛起時需調用MapView.onPause()mMapView.onPause();super.onPause();}@Overrideprotected void onResume() {// MapView的生命周期與Activity同步,當activity掛起時需調用MapView.onPause()mMapView.onResume();super.onResume();}@Overrideprotected void onDestroy() {// MapView的生命周期與Activity同步,當activity銷毀時需調用MapView.destroy()mMapView.destroy();// 退出應用調用BMapManager的destroy()方法if (mapManager != null) {mapManager.destroy();mapManager = null;}super.onDestroy();}public void onGetNetworkState(int arg0) {}public void onGetPermissionState(int arg0) {}@SuppressLint("Override")class ReadHttpGet extends AsyncTask<Object, Object, Object> {@Overrideprotected Object doInBackground(Object... params) {HttpGet httpRequest = new HttpGet(params[0].toString());try {HttpClient httpClient = new DefaultHttpClient();HttpResponse httpResponse = httpClient.execute(httpRequest);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String strResult = EntityUtils.toString(httpResponse.getEntity());return strResult;} else {return "請求出錯";}} catch (ClientProtocolException e) {} catch (IOException e) {e.printStackTrace();}return null;}protected void onCancelled(Object result) {super.onCancelled();}@SuppressLint("Override")@Overrideprotected void onPostExecute(Object result) {super.onPostExecute(result);mMapView.regMapViewListener(mapManager, new MKMapViewListener() {// * 地圖移動完成時會回調此接口 方法public void onMapMoveFinish() {showToast("地圖移動完畢!");}// * 地圖加載完畢回調此接口方法public void onMapLoadFinish() {showToast("地圖載入完畢!");}// * 地圖完成帶動畫的操作(如: animationTo())后,此回調被觸發public void onMapAnimationFinish() {}// * 點擊地圖上被標記的點回調此方法public void onClickMapPoi(MapPoi arg0) {if (arg0 != null) {showToast(arg0.strText);}}// 當調用過 mMapView.getCurrentMap()后,此回調會被觸發 可在此保存截圖至存儲設備public void onGetCurrentMap(Bitmap arg0) {// TODO Auto-generated method stub}});try {// 創建一個JSON對象JSONObject jsonObject = new JSONObject(result.toString()).getJSONObject("parent");// 獲取某個對象的JSON數組JSONArray jsonArray = jsonObject.getJSONArray("children");StringBuilder builder = new StringBuilder();for (int i = 0; i < jsonArray.length(); i++) {// 新建一個JSON對象,該對象是某個數組里的其中一個對象JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);Map<String, Object> map = new HashMap<String, Object>();map.put("id", jsonObject2.getString("id"));map.put("name", jsonObject2.getString("name"));map.put("depth", jsonObject2.getString("depth"));map.put("lgtd", jsonObject2.getString("lgtd"));map.put("lttd", jsonObject2.getString("lttd"));curData.add(map);}Drawable marker = getResources().getDrawable(R.drawable.map_yqtag); // 得到需要標在地圖上的資源marker.setBounds(0, 0, marker.getIntrinsicWidth(),marker.getIntrinsicHeight()); // 為maker定義位置和邊界OverItemCrossBridgeInfo itemOverlay = new OverItemCrossBridgeInfo(marker,SYIT_SSJC.this,curData,mMapView);// 繪制文字TextOverlay textOverlay = new TextOverlay(mMapView);mMapView.getOverlays().clear();for (int i = 0; i < jsonArray.length(); i++) {// 新建一個JSON對象,該對象是某個數組里的其中一個對象JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);// 準備要添加的Overlaydouble mLat1 = Double.valueOf(jsonObject2.getString("lttd"));double mLon1 = Double.valueOf(jsonObject2.getString("lgtd"));// 用給定的經緯度構造GeoPoint,單位是微度 (度 * 1E6)GeoPoint p1 = new GeoPoint((int) (mLat1 * 1E6), (int) (mLon1 * 1E6));mMapController.setCenter(p1);// 用OverlayItem準備Overlay數據OverlayItem item1 = new OverlayItem(p1, jsonObject2.getString("name"), jsonObject2.getString("depth"));// 現在所有準備工作已準備好,使用以下方法管理overlay.// 添加overlay, 當批量添加Overlay時使用addItem(List<OverlayItem>)效率更高itemOverlay.addItem(item1);//mMapView.getOverlays().add(textOverlay);textOverlay.addText(drawText(mLat1,mLon1,jsonObject2.getString("name")+" "+jsonObject2.getString("depth")+"cm"));}// 將IteminizedOverlay添加到MapView中mMapView.getOverlays().add(textOverlay);mMapView.getOverlays().add(itemOverlay);mMapView.refresh();System.out.println(builder.toString());//加載設置地圖中心點位置initMap();} catch (JSONException e) {e.printStackTrace();}}protected void onPreExecute() {Toast.makeText(getApplicationContext(), "開始HTTP GET請求",Toast.LENGTH_LONG).show();}protected void onProgressUpdate(Object... values) {super.onProgressUpdate(values);}}/*** 繪制文字,該文字隨地圖變化有透視效果* * @return 文字對象*/public TextItem drawText(double mLat,double mLon,String text) {int lat = (int) (mLat * 1E6);int lon = (int) (mLon * 1E6);// 構建文字TextItem item = new TextItem();// 設置文字位置item.pt = new GeoPoint(lat, lon);// 設置文件內容item.text = text;// 設文字大小item.fontSize = 30;Symbol symbol = new Symbol();Symbol.Color bgColor = symbol.new Color();// 設置文字背景色bgColor.red = 0;bgColor.blue = 0;bgColor.green = 255;bgColor.alpha = 50;Symbol.Color fontColor = symbol.new Color();// 設置文字著色fontColor.alpha = 255;fontColor.red = 0;fontColor.green = 0;fontColor.blue = 255;// 設置對齊方式item.align = TextItem.ALIGN_CENTER;// 設置文字顏色和背景顏色item.fontColor = fontColor;//item.bgColor = bgColor;return item;}/*** 設置地圖的坐標點在最中心顯示*/public void initMap(){GeoPoint p; // 保存精度和緯度的類,double eastMax = 0.0; //經度最大值 東double southMin = 0.0; //緯度最小值 南double westMin = 0.0; //經度最小值 西double northMax = 0.0; //緯度最大值 北double eastX = 0.0; //經度最大值 東double eastY = 0.0; //經度最大值 東double southX = 0.0; //緯度最小值 南double southY = 0.0; //緯度最小值 南double westX = 0.0; //經度最小值 西double westY = 0.0; //經度最小值 西double northX = 0.0; //緯度最大值 北double northY = 0.0; //緯度最大值 北for (int i = 0; i < curData.size(); i++) // 計算經緯度中心點 先計算出最東、最西、最南、最北四個點 {Map<String, Object> mapItem = curData.get(i);double lttd = Double.parseDouble(mapItem.get("lttd").toString());double lgtd = Double.parseDouble(mapItem.get("lgtd").toString());if(lgtd > eastMax) // 獲取經度最大值 東eastMax = lgtd;if(lttd < southMin || southMin == 0.0) // 獲取緯度最小值 南southMin = lttd;if(lgtd < westMin || westMin == 0.0) // 獲取經度最小值 西westMin = lgtd;if(lttd > northMax) // 獲取緯度最大值 北northMax = lttd;}Log.i(xmTools.Tag, "經度最大值 :" + eastMax + "緯度最小值:" + southMin + "經度最小值 :" + eastMax + "緯度最大值:" + southMin);for (int i = 0; i < curData.size(); i++) // 計算經緯度中心點 先計算出最東、最西、最南、最北四個點 {Map<String, Object> mapItem = curData.get(i);double lttd = Double.parseDouble(mapItem.get("lttd").toString());double lgtd = Double.parseDouble(mapItem.get("lgtd").toString());// 獲取經度最大值 東if(lgtd == eastMax){eastX = lgtd;eastY = lttd;}// 獲取緯度最小值 南if(lttd == southMin){southX = lgtd;southY = lttd;}// 獲取經度最小值 西if(lgtd == westMin){westX = lgtd;westY = lttd;}// 獲取緯度最大值 北if(lttd == northMax){northX = lgtd;northY = lttd;}}// 計算最東南西北四個坐標的中心點 設置p地方為中心點double centerX = eastX - ((eastX - westX)/2);double centerY = northY - ((northY - southY) /2);p = new GeoPoint( (int)(centerY * 1e6 ) ,(int)(centerX * 1e6));// 計算地圖縮放比例// 設置地圖縮放級別int spanLatDelta = (int) ((int) (Math.abs((eastX - westX) * 1e6) ) * 1.1);int spanLngDelta = (int) ((int) (Math.abs((northY - southY) * 1e6) ) * 1.1);double temp1 = spanLatDelta;double temp2 = spanLngDelta;mMapController.zoomToSpan(spanLatDelta, spanLngDelta);//設置中心點經緯度mMapController.animateTo(p); // mMapController.setCenter(p);}/*** 地圖標記類**/class OverItemCrossBridgeInfo extends ItemizedOverlay<OverlayItem> {public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();private Drawable marker;private Context mContext;private double mLat3 = 39.90923;private double mLon3 = 116.437428;private List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();public OverItemCrossBridgeInfo(Drawable marker, Context context, List<Map<String,Object>> allArray,MapView mapView) {super(marker,mapView);//得到需要標在地圖上的資源Drawable markerGreen = context.getResources().getDrawable(R.drawable.map_yqtag); //為maker定義位置和邊界markerGreen.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight()); this.marker = marker;this.mContext = context;this.list = allArray;// 處理經緯度坐標for (int i = 0; i < list.size(); i++) {Map<String, Object> mapItem = list.get(i);//賦值給字符串 // String idStr = mapItem.get("id").toString();String name = mapItem.get("name").toString();String ydStr = mapItem.get("depth").toString();double lttd = Double.parseDouble(mapItem.get("lttd").toString() );double lgtd = Double.parseDouble(mapItem.get("lgtd").toString() );GeoPoint p1 = new GeoPoint((int) (lttd * 1E6),(int) (lgtd * 1E6));OverlayItem myPosOverlayitem = new OverlayItem(p1, name, name);mGeoList.add(myPosOverlayitem);//繪制文字TextOverlay textOverlay = new TextOverlay(mapView);mapView.getOverlays().add(textOverlay);textOverlay.addText(drawText(lttd, lgtd, name));}this.addItem(mGeoList);}@Override// 處理當點擊事件protected boolean onTap(int i) {try{Map<String, Object> mapItem = list.get(i);//賦值給字符串String stringId = mapItem.get("id").toString();String name = mapItem.get("name").toString();String ym = mapItem.get("depth").toString();SYIT_SSJC_Detail.crossBridgeID = stringId;SYIT_SSJC_Detail.crossBridgeName = name;Toast.makeText(this.mContext, mGeoList.get(i).getSnippet(),Toast.LENGTH_SHORT).show();Intent intent = new Intent(this.mContext, SYIT_SSJC_Detail.class);this.mContext.startActivity(intent);return true;}catch(Exception e){return false;}}@Overridepublic boolean onTap(GeoPoint arg0, MapView arg1) {// TODO Auto-generated method stub// 消去彈出的氣泡// ItemizedOverlayDemo.mPopView.setVisibility(View.GONE);return super.onTap(arg0, arg1);}} }
總結
以上是生活随笔為你收集整理的Android加载百度地图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring源码深入阅读Annotati
- 下一篇: MLAT-Autoencoders fo