
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" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:background="#FFFF00" >
<LinearLayout
android:id="@+id/yqxx_table_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFF00"
android:orientation="vertical" >
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/back" />
</LinearLayout>
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:orientation="horizontal" >
<Button
android: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" />
<Button
android: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() {
@Override
public 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;
}
}
@Override
protected void onPause() {
// MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause()
mMapView.onPause();
super.onPause();
}
@Override
protected void onResume() {
// MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause()
mMapView.onResume();
super.onResume();
}
@Override
protected 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> {
@Override
protected 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")
@Override
protected 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);
// 准备要添加的Overlay
double 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;
}
}
@Override
public boolean onTap(GeoPoint arg0, MapView arg1) {
// TODO Auto-generated method stub
// 消去弹出的气泡
// ItemizedOverlayDemo.mPopView.setVisibility(View.GONE);
return super.onTap(arg0, arg1);
}
}
}