百度地图实现与总结..
因为公司用到百度地图比较多,所以就自己给自己总结总结:
想要使用百度地图, 1. 你要先注册1个百度账号(到时候申请key需要)
2. 需要百度的SDK
1.2都很简单,可以自行解决了。--- 说实话 官网上的 demo 真心也很详细呢 = = 网址:http://developer.baidu.com/map/sdkandev-6.htm#.E7.AE.80.E4.BB.8B4
现在看下工程
把 需要的东西全部放进工程。
然后就开始看代码吧(---部分代码哦---)。
public class MapActivity extends SherlockActivity implements ActionBar.OnNavigationListener{
private ProgressDialogView progressDialog =null;
public BMapManager mapManager = null;
public MKMapViewListener mMapListtener = null;
public MapView mapView;
public MapController mapController;
private PopupOverlay pop;
private LocationListener locationListener;
private MapActivity Instance;
private List<PersonInfo> list_person = null;
private List<OverlayItem> list_overlayItem;
private OverlayMain overlayMain;
private LocationClient locationClient;
private LocationData locationData;
private MyLocationOverlay myLocationOverlay;
private GeoPoint currentGP = null;
private GeoPoint pGP = null;
//获取数据的
private AlarmManager alarManager;
private PendingIntent pendingIntent;
private ImageButton show_mylocation_button;
public final int INTERENT_FAILD = 123;
private Handler han = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
if( progressDialog.isShowing()){
progressDialog.dismiss();
}
list_person = (List<PersonInfo>)msg.obj;
list_overlayItem = null;
mapView.getOverlays().clear();
addAllOverlayItem();
mapView.refresh();
break;
case 2:
System.out.println("han222222222------");
Vector v =(Vector)msg.obj;
// overlayMain = null;
mapView.getOverlays().clear();
mapView.refresh();
list_overlayItem = null;
addItem(v);
mapView.refresh();
break;
case 11:
mapView.getOverlays().add(myLocationOverlay);
mapView.refresh();
break;
case INTERENT_FAILD:
if( progressDialog.isShowing()){
progressDialog.dismiss();
}
Toast.makeText(getApplicationContext(), "获取数据失败",
Toast.LENGTH_LONG).show();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
this.setTheme(R.style.Theme_MyTheme);
super.onCreate(savedInstanceState);
mapManager = new BMapManager(getApplication());
try {
mapManager.init(Commons.MapKey, new MKGeneralListener() {
@Override
public void onGetPermissionState(int station) {
if(station == MKEvent.ERROR_NETWORK_CONNECT){
Toast.makeText(getApplicationContext(),"您的网络出错了!",Toast.LENGTH_LONG).show();
}else if(station == MKEvent.ERROR_NETWORK_DATA ){
Toast.makeText(getApplicationContext(), "输入正确的检索条件!", Toast.LENGTH_LONG).show();
}
}
@Override
public void onGetNetworkState(int station) {
if(station == MKEvent.ERROR_PERMISSION_DENIED){
Toast.makeText(getApplicationContext(), "请在Main.java文件输入正确的授权Key!",
Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
}
setContentView(R.layout.activity_map);
show_mylocation_button = (ImageButton)this.findViewById(R.id.map_mylocation_button);
initActionBar();
show_mylocation_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message message = new Message();
message.what = 11;
han.sendMessage(message);
}
});
Instance =this;
mapView =(MapView)this.findViewById(R.id.emlo_mapView);
mapView.setBuiltInZoomControls(true); //启用缩放控件
mapView.getController().enableClick(true);
// overlayMain = new OverlayMain(null , mapView , Instance , list_person);
mapController = mapView.getController();
mapController.setZoom(Commons.MapZoom);
//设置地图中心点
//初始化模块 ,注册事件
initMyLocation();
progressDialog = new ProgressDialogView(MapActivity.this, "获取地图数据中..");
progressDialog.show();
getDate();
}
private void initMyLocation(){
try {
locationClient = new LocationClient(this);
locationData = new LocationData();
locationClient.registerLocationListener(new MyLocationListener());
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); //打开 GPS
option.setCoorType("bd09ll"); //设置坐标类型
option.setScanSpan(1000); // 1秒定位一次
option.setAddrType("all");
option.setPriority(LocationClientOption.NetWorkFirst); //设置网络有限
//option.disableCache(true);// true表示禁用缓存定位,false表示启用缓存定位
//option.setProdName(name) 定位设置项目name
locationClient.setLocOption(option);
locationClient.start();
myLocationOverlay = new MyLocationOverlay(mapView);
//mapView.getOverlays().add(myLocationOverlay);
//myLocationOverlay.enableCompass();//开启指南针
mapView.refresh();
} catch (Exception e) {
// TODO: handle exception
}
}
public void getDate(){
new Thread(new Runnable() {
@Override
public void run() {
try {
SoapObject soapObject = (SoapObject) WebConn.GetWebServiceData(Commons.NameSpace,
Commons.Method, Commons.DZURL, null);
System.out.println("soapObject"+ soapObject.toString());
List<PersonInfo> ll= FormatData.getResult(soapObject);
Message message = new Message();
message.what = 1;
message.obj = ll;
han.sendMessage(message);
} catch (Exception e) {
han.sendEmptyMessage(INTERENT_FAILD);
}
}
}).start();
}
public void addAllOverlayItem (){
Drawable marker = getResources().getDrawable(R.drawable.l3);
OverlayItem overlayItem =null;
GeoPoint mapPoint;
double jingdu;
double weidu;
list_overlayItem = new ArrayList<OverlayItem>();
if(list_person != null){
for (PersonInfo pi : list_person) {
weidu = Double.parseDouble(pi.Latitude);
jingdu =Double.parseDouble(pi.Longitude);
String person = "姓名:" + pi.Name ;
String info = "部门:" + pi.DepartmentName + " "+
"电话:" + pi.PhoneNumber + " "+
"最后更新时间:"+ pi.UpdateTime ;
mapPoint = new GeoPoint((int )(weidu * 1E6), (int )(jingdu * 1E6));
overlayItem = new OverlayItem(mapPoint, person , info); //覆盖物的这个值你可以取出来弄别的你想弄的事情= =
View view = MapActivity.this.getLayoutInflater().inflate(R.layout.pop_simple, null);
TextView person_name = (TextView)view.findViewById(R.id.person_simple_name);
person_name.setText( pi.Name );
Bitmap bit_map = BitmapUtil.convertViewToBitMap(view);
BitmapDrawable market = new BitmapDrawable(getResources(),bit_map);
overlayItem.setMarker(market);
list_overlayItem.add(overlayItem);
}
overlayMain = new OverlayMain(null , mapView , Instance , list_person);
overlayMain.addItem(list_overlayItem);
mapView.getOverlays().add(overlayMain);
}
}
//时刻定位本人的位置
private class MyLocationListener implements BDLocationListener{
@Override
public void onReceiveLocation(BDLocation bdLocation) {
if(bdLocation == null){
return;
}
//个人位置的相数据
locationData.latitude = bdLocation.getLatitude(); //纬度
locationData.longitude = bdLocation.getLongitude(); //精度
locationData.accuracy = bdLocation.getRadius(); //获取服务
myLocationOverlay.setData(locationData);
currentGP = new GeoPoint((int)(locationData.latitude * 1E6), (int)(locationData.longitude * 1E6));
try {
mapController.setCenter(currentGP);
mapView.refresh();
} catch (Exception e) {
System.out.println(e.toString());
}
}
@Override
public void onReceivePoi(BDLocation bdLocation) {
//这个----------------------------------------------------后面也会详细j
}
}
@Override
protected void onStop() {
System.out.println("map_ononStop-----");
super.onStop();
}
@Override
protected void onNewIntent(Intent intent) {
System.out.println("map-onNewIntent--");
String jingdu =intent.getStringExtra("jingdu");
String weidu = intent.getStringExtra("weidu");
String name =intent.getStringExtra("name");
String depart=intent.getStringExtra("depart");
String phone=intent.getStringExtra("phone");
String updatetime=intent.getStringExtra("updatetime");
Vector v = new Vector();
v.add(jingdu);
v.add(weidu);
v.add(name);
v.add(depart);
v.add(phone);
v.add(updatetime);
Message message = new Message();
message.what = 2;
message.obj = v;
han.sendMessage(message);
}
public void addItem(Vector v){
Drawable marker = getResources().getDrawable(R.drawable.l3);
OverlayItem overlayItem =null;
GeoPoint mapPoint;
double jingdu;
double weidu;
list_overlayItem = new ArrayList<OverlayItem>();
jingdu =Double.parseDouble(v.get(0).toString()); //jingdu xiao
weidu = Double.parseDouble(v.get(1).toString()); //weidu da
String person = "姓名:" + v.get(2).toString() ;
String info = "部门:" + v.get(3).toString() + "\n"+
"电话:" + v.get(4).toString() + "\n"+
"最后更新时间:"+ v.get(5).toString() ;
mapPoint = new GeoPoint((int )(jingdu * 1E6), (int )(weidu * 1E6));
overlayItem = new OverlayItem(mapPoint, person , info); //覆盖物的这个值你可以取出来弄别的你想弄的事情= =
View view = MapActivity.this.getLayoutInflater().inflate(R.layout.pop, null);
TextView person_name = (TextView)view.findViewById(R.id.person_name);
TextView person_depart = (TextView)view.findViewById(R.id.person_depart);
TextView person_phone = (TextView)view.findViewById(R.id.person_phone);
TextView person_lasttime = (TextView)view.findViewById(R.id.person_updatetime);
person_name.setText("姓名:" + v.get(2).toString());
person_depart.setText("部门:"+ v.get(3).toString());
person_phone.setText("电话:"+ v.get(4).toString());
person_lasttime.setText("最后更新时间:"+ v.get(5).toString()+"小时前");
GeoPoint geoPoint = new GeoPoint((int )(Double.parseDouble(v.get(0).toString()) * 1E6),
(int )(Double.parseDouble(v.get(1).toString()) * 1E6));
Bitmap bit_map = BitmapUtil.convertViewToBitMap(view);
BitmapDrawable market = new BitmapDrawable(getResources(),bit_map);
overlayItem.setMarker(market);
list_overlayItem.add(overlayItem);
// overlayMain.addItem(overlayItem);
overlayMain = new OverlayMain(null , mapView , Instance , list_person);
overlayMain.addItem(list_overlayItem);
mapView.getOverlays().add(overlayMain);
}
@Override
protected void onRestart() {
System.out.println("map_onRestart-----");
super.onRestart();
}
@Override
protected void onDestroy() {
System.out.println("map_onDestroy-----");
if(locationClient!= null){
locationClient.stop();
}
if( mapManager != null){
mapManager.destroy();
mapManager = null;
}
mapView.destroy();
super.onDestroy();
}
//-------------------------- actionBar ----------------- 的一些操作(后面也会详细说说 actionbar)-------------------
public void initActionBar(){
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setTitle("辽宁省环境保护厅定位系统");
}
@Override
public boolean onCreatePanelMenu(int featureId, com.actionbarsherlock.view.Menu menu) {
SubMenu subMenu = menu.addSubMenu("");
subMenu.add(0, 1, 0, "刷新");
subMenu.add(0, 1, 1, "人员列表");
subMenu.setIcon(R.drawable.ic_action_overflow);
MenuItem subMenuItem = subMenu.getItem();
subMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
super.onCreateOptionsMenu(menu);
return true;
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == 1){
switch (item.getOrder()) {
case 0: //刷新
progressDialog = new ProgressDialogView(MapActivity.this, "正在获取数据");
progressDialog.show();
getDate();
break;
case 1: //进入人员列表
this.startActivity(new Intent().setClass(this, EmployeeListActivity.class));
break;
}
}
return false;
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
return false;
}
// 定时的功能
public void dingshi(){
alarManager =(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent in= new Intent().setAction("com.lvchuang.ws");
int requestCode =0 ;
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
requestCode, in, PendingIntent.FLAG_UPDATE_CURRENT);
int n = (int) (SystemClock.elapsedRealtime() + Commons.nn);
// n秒后发送 循环 nn 发送
alarManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, n, Commons.nn, pendingIntent);
//alarManager.cancel(operation)取消
//alarManager = null;
}
}
自定义图层
- /*
- *要处理overlay点击事件时需要继承ItemizedOverlay
- *不处理点击事件时可直接生成ItemizedOverlay.
- */
- classOverlayTestextendsItemizedOverlay<OverlayItem>{
- //用MapView构造ItemizedOverlay
- publicOverlayTest(Drawablemark,MapViewmapView){
- super(mark,mapView);
- }
- protectedbooleanonTap(intindex){
- //在此处理item点击事件
- System.out.println("itemonTap:"+index);
- returntrue;
- }
- publicbooleanonTap(GeoPointpt,MapViewmapView){
- //在此处理MapView的点击事件,当返回true时
- super.onTap(pt,mapView);
- returnfalse;
- }
- //自2.1.1开始,使用add/remove管理overlay,无需重写以下接口
- /*
- @Override
- protectedOverlayItemcreateItem(inti){
- returnmGeoList.get(i);
- }
- @Override
- publicintsize(){
- returnmGeoList.size();
- }
- */
- }
因为 直接很多的例子很多,所以我就结合自己部分应用的代码直接贴出来了。想要更详细的了解还是要看,文章的开头 百度地图官网,例子注释狠详细。
下面拿过来的
- <!--使用网络功能所需权限-->
- <uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
-
- <uses-permissionandroid:name="android.permission.INTERNET"/>
-
- <uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>
-
- <uses-permissionandroid:name="android.permission.CHANGE_WIFI_STATE"/>
-
- <!--SDK离线地图和cache功能需要读写外部存储器-->
- <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-
- <!--获取设置信息和详情页直接拨打电话需要以下权限-->
- <uses-permissionandroid:name="android.permission.READ_PHONE_STATE"/>
-
- <uses-permissionandroid:name="android.permission.CALL_PHONE"/>
- <!--使用定位功能所需权限,demo已集成百度定位SDK,不使用定位功能可去掉以下6项-->
- <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>
-
- <permissionandroid:name="android.permission.BAIDU_LOCATION_SERVICE"/>
-
- <uses-permissionandroid:name="android.permission.BAIDU_LOCATION_SERVICE"/>
- <uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
-
- <uses-permissionandroid:name="android.permission.ACCESS_MOCK_LOCATION"/>
-
- <uses-permissionandroid:name="android.permission.ACCESS_GPS"/>
配置Activity:
横竖屏切换后Activity会重新执行onCreat函数,但是在Android工程的Mainfest.xml中加入android:screenOrientation="user"
android:configChanges="orientation|keyboardHidden"之后,横竖屏切换之后就不会去执行OnCreat函数了,而是会去调用onConfigurationChanged(),这样我们就能控制横竖屏的切换了。
- <activityandroid:name=".MapDemo"
- android:screenOrientation="sensor"
- android:configChanges="orientation|keyboardHidden">
- </activity>
添加屏幕及版本支持:
- <supports-screensandroid:largeScreens="true"
- android:normalScreens="true"
- android:smallScreens="true"
- android:resizeable="true"
- android:anyDensity="true"/>
- <uses-sdkandroid:minSdkVersion="7"></uses-sdk>
第三步:在布局xml文件中添加地图控件,布局文件保存为activity_main.xml:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextViewandroid:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="helloworld"/>
- <com.baidu.mapapi.map.MapViewandroid:id="@+id/bmapsView"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:clickable="true"/>
- </LinearLayout>