BaiduMap---百度地图官方Demo之离线地图功能(介绍如何下载和使用离线地图)

<?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
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/cityid"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="131" />
        <!-- 隐藏输入法用 -->

        <LinearLayout
            android:layout_width="0px"
            android:layout_height="0px"
            android:focusable="true"
            android:focusableInTouchMode="true" />

        <EditText
            android:id="@+id/city"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="北京" />

        <Button
            android:id="@+id/search"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/button_style"
            android:onClick="search"
            android:text="搜索" />

        <Button
            android:id="@+id/scan"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/button_style"
            android:onClick="importFromSDCard"
            android:text="导入" />
    </LinearLayout>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/state"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="已下载:--" />

        <Button
            android:id="@+id/start"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/button_style"
            android:onClick="start"
            android:text="开始" />

        <Button
            android:id="@+id/stop"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/button_style"
            android:onClick="stop"
            android:text="停止" />

        <Button
            android:id="@+id/del"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/button_style"
            android:onClick="remove"
            android:text="删除" />
    </LinearLayout>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/city_list"
        android:layout_width="match_parent"
        android:layout_height="50dip"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/clButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/button_style"
            android:onClick="clickCityListButton"
            android:text="城市列表" />

        <Button
            android:id="@+id/localButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/button_style"
            android:onClick="clickLocalMapListButton"
            android:text="下载管理" />
    </LinearLayout>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/citylist_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="热门城市" />

        <ListView
            android:id="@+id/hotcitylist"
            android:layout_width="fill_parent"
            android:layout_height="200dip" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="全国" />

        <ListView
            android:id="@+id/allcitylist"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </LinearLayout>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/localmap_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="已下载城市 " />

        <ListView
            android:id="@+id/localmaplist"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>




/**
 * 介绍如何下载和使用离线地图
 * */
public class OfflineDemo extends Activity implements MKOfflineMapListener {
	/**
	 * 离线地图服务
	 * 用于管理离线地图.
	 * */
	private MKOfflineMap mOffline = null;
	private TextView cidView;
	private TextView stateView;
	private EditText cityNameView;
	/**
	 * 已下载的离线地图信息列表
	 * MKOLUpdateElement:离线地图更新信息
	 */
	private ArrayList<MKOLUpdateElement> localMapList = null;
	private LocalMapAdapter lAdapter = null;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_offline);
		
		mOffline = new MKOfflineMap();
		/**
		 * public boolean init(MKOfflineMapListener listener)
		 * 初使化
		 * 返回:成功返回true,否则返回false
		 * 
		 * 需要实现MKOfflineMapListener的onGetOfflineMapState(int type, int state)方法
		 * */
		mOffline.init(this);
		
		initView();

	}

	private void initView() {
		//城市id
		cidView = (TextView) findViewById(R.id.cityid);
		//城市名称
		cityNameView = (EditText) findViewById(R.id.city);
		//下载状态
		stateView = (TextView) findViewById(R.id.state);
		//热门城市列表
		ListView hotCityList = (ListView) findViewById(R.id.hotcitylist);
		
		ArrayList<String> hotCities = new ArrayList<String>();
		// 获取热闹城市列表
		ArrayList<MKOLSearchRecord> records1 = mOffline.getHotCityList();
		
		if (records1 != null) {
			/**
			 * MKOLSearchRecord:离线地图搜索城市记录结构
			 * cityID:城市ID
			 * size:数据包总大小
			 * */
			for (MKOLSearchRecord r : records1) {
				hotCities.add(r.cityName + "(" + r.cityID + ")" + "   --"+ this.formatDataSize(r.size));
			}
		}
		ListAdapter hAdapter = (ListAdapter) new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, hotCities);
		hotCityList.setAdapter(hAdapter);
		
		//所有城市列表
		ListView allCityList = (ListView) findViewById(R.id.allcitylist);
		// 获取所有支持离线地图的城市
		ArrayList<String> allCities = new ArrayList<String>();
		
		/**
		 * public java.util.ArrayList<MKOLSearchRecord> getOfflineCityList()
		 * 返回支持离线地图城市列表
		 * 返回:支持离线地图城市列表
		 * */
		ArrayList<MKOLSearchRecord> records2 = mOffline.getOfflineCityList();
		
		if (records1 != null) {
			for (MKOLSearchRecord r : records2) {
				allCities.add(r.cityName + "(" + r.cityID + ")" + "   --"+ this.formatDataSize(r.size));
			}
		}
		
		ListAdapter aAdapter = (ListAdapter) new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, allCities);
		allCityList.setAdapter(aAdapter);

		LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
		LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
		lm.setVisibility(View.GONE);
		cl.setVisibility(View.VISIBLE);

		// 获取已下过的离线地图信息
		localMapList = mOffline.getAllUpdateInfo();
		if (localMapList == null) {
			localMapList = new ArrayList<MKOLUpdateElement>();
		}

		ListView localMapListView = (ListView) findViewById(R.id.localmaplist);
		lAdapter = new LocalMapAdapter();
		localMapListView.setAdapter(lAdapter);

	}

	/**
	 * 搜索按钮点击事件
	 * 
	 * 搜索离线需市
	 * @param view
	 */
	public void search(View view) {
		/**
		 * public java.util.ArrayList<MKOLSearchRecord> searchCity(java.lang.String cityName)
		 * 根据城市名搜索该城市离线地图记录
		 * 参数:cityName - 城市名
		 * 返回: 该城市离线地图记录
		 * */
		//从输入框中获取城市,查询该城市的离线地图搜索城市记录结构
		ArrayList<MKOLSearchRecord> records = mOffline.searchCity(cityNameView.getText().toString());
		if (records == null || records.size() != 1)
			return;
		//显示查找出来的城市id
		cidView.setText(String.valueOf(records.get(0).cityID));
	}
	
	/**
	 * 导入按钮点击事件
	 * 
	 * 从SD卡导入离线地图安装包
	 * @param view
	 */
	public void importFromSDCard(View view) {
		/**
		 * public int importOfflineData()
		 * 导入离线地图包
		 * */
		int num = mOffline.importOfflineData();
		String msg = "";
		if (num == 0) {
			msg = "没有导入离线包,这可能是离线包放置位置不正确,或离线包已经导入过";
		} else {
			msg = String.format("成功导入 %d 个离线包,可以在下载管理查看", num);
		}
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
		updateView();
	}


	/**
	 * 开始按钮点击事件
	 * 
	 * 开始下载
	 * @param view
	 */
	public void start(View view) {
		int cityid = Integer.parseInt(cidView.getText().toString());
		/**
		 * public boolean start(int cityID)
		 * 启动下载指定城市ID的离线地图
		 * 参数:cityID - 指定的城市ID
		 * 返回:成功返回true,否则返回false
		 * */
		mOffline.start(cityid);
		
		//设置下载管理点击时间按钮响应为空
		clickLocalMapListButton(null);
		Toast.makeText(this, "开始下载离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();
		updateView();
	}

	/**
	 * 停止按钮点击事件
	 * 
	 * 暂停下载
	 * @param view
	 */
	public void stop(View view) {
		int cityid = Integer.parseInt(cidView.getText().toString());
		
		/**
		 * public boolean pause(int cityID)
		 * 暂停下载指定城市ID的离线地图
		 * 参数:cityID - 指定的城市ID
		 * 返回:成功返回true,否则返回false
		 * */
		mOffline.pause(cityid);
		Toast.makeText(this, "暂停下载离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();
		updateView();
	}

	/**
	 * 删除按钮点击事件
	 * 
	 * 删除离线地图
	 * @param view
	 */
	public void remove(View view) {
		int cityid = Integer.parseInt(cidView.getText().toString());
		/**
		 * public boolean remove(int cityID)
		 * 删除指定城市ID的离线地图
		 * 参数:cityID - 指定的城市ID
		 * 返回:成功返回true,否则返回false
		 * */
		mOffline.remove(cityid);
		Toast.makeText(this, "删除离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();
		updateView();
	}

	/**
	 * 城市列表按钮点击事件
	 * 
	 * 切换至城市列表
	 * @param view
	 */
	public void clickCityListButton(View view) {
		//城市列表
		LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
		LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
		lm.setVisibility(View.GONE);
		cl.setVisibility(View.VISIBLE);

	}

	/**
	 * 下载管理按钮点击事件
	 * 
	 * 切换至下载管理列表
	 * @param view
	 */
	public void clickLocalMapListButton(View view) {
		LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
		//已下载城市
		LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
		lm.setVisibility(View.VISIBLE);
		cl.setVisibility(View.GONE);
	}
	
	/**
	 * 更新状态显示
	 */
	public void updateView() {
		/**
		 * public java.util.ArrayList<MKOLUpdateElement> getAllUpdateInfo()
		 * 返回各城市离线地图更新信息
		 * 返回:各城市离线地图更新信息
		 * */
		localMapList = mOffline.getAllUpdateInfo();
		if (localMapList == null) {
			localMapList = new ArrayList<MKOLUpdateElement>();
		}
		lAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onPause() {
		int cityid = Integer.parseInt(cidView.getText().toString());
		MKOLUpdateElement temp = mOffline.getUpdateInfo(cityid);
		/**
		 * MKOLUpdateElement:离线地图更新信息
		 * status:下载状态
		 * */
		if (temp != null && temp.status == MKOLUpdateElement.DOWNLOADING) {
			mOffline.pause(cityid);
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public String formatDataSize(int size) {
		String ret = "";
		if (size < (1024 * 1024)) {
			ret = String.format("%dK", size / 1024);
		} else {
			ret = String.format("%.1fM", size / (1024 * 1024.0));
		}
		return ret;
	}

	@Override
	protected void onDestroy() {
		/**
		 * 退出时,销毁离线地图模块
		 */
		mOffline.destroy();
		super.onDestroy();
	}
	
	/**
	 * void onGetOfflineMapState(int type,int state)
	 * 返回通知事件
	 * 参数:
	 * type - 事件类型: MKOfflineMap.TYPE_NEW_OFFLINE, 
	 * 				  MKOfflineMap.TYPE_DOWNLOAD_UPDATE, 
	 *                MKOfflineMap.TYPE_VER_UPDATE.
	 * state - 事件状态: 当type为TYPE_NEW_OFFLINE时,表示新安装的离线地图数目. 
	 *                 当type为TYPE_DOWNLOAD_UPDATE时,表示更新的城市ID.
	 * */
	@Override
	public void onGetOfflineMapState(int type, int state) {
		switch (type) {
		//离线地图下载更新事件类型
		case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
			/**
			 * public MKOLUpdateElement getUpdateInfo(int cityID)
			 * 返回指定城市ID离线地图更新信息
			 * 返回:该城市离线地图更新信息
			 * */
			MKOLUpdateElement update = mOffline.getUpdateInfo(state);
			// 处理下载进度更新提示
			if (update != null) {
				//cityName:城市名称;
				//ratio:下载比率,100为下载完成
				stateView.setText(String.format("%s : %d%%", update.cityName,update.ratio));
				updateView();
			}
		}
			break;
			
		//新安装离线地图事件类型
		case MKOfflineMap.TYPE_NEW_OFFLINE:
			// 有新离线地图安装
			Log.d("OfflineDemo", String.format("add offlinemap num:%d", state));
			break;
			
		//离线地图数据版本更新事件类型	
		case MKOfflineMap.TYPE_VER_UPDATE:
			// 版本更新提示
			// MKOLUpdateElement e = mOffline.getUpdateInfo(state);
			break;
		}

	}

	/**
	 * 离线地图管理列表适配器
	 */
	public class LocalMapAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return localMapList.size();
		}

		@Override
		public Object getItem(int index) {
			return localMapList.get(index);
		}

		@Override
		public long getItemId(int index) {
			return index;
		}

		@Override
		public View getView(int index, View view, ViewGroup arg2) {
			MKOLUpdateElement e = (MKOLUpdateElement) getItem(index);
			view = View.inflate(OfflineDemo.this,R.layout.offline_localmap_list, null);
			initViewItem(view, e);
			return view;
		}

		void initViewItem(View view, final MKOLUpdateElement e) {
			//查看
			Button display = (Button) view.findViewById(R.id.display);
			//删除
			Button remove = (Button) view.findViewById(R.id.remove);
			//城市
			TextView title = (TextView) view.findViewById(R.id.title);
			//更新
			TextView update = (TextView) view.findViewById(R.id.update);
			//比率
			TextView ratio = (TextView) view.findViewById(R.id.ratio);
			
			ratio.setText(e.ratio + "%");
			title.setText(e.cityName);
			
			/**
			 * MKOLUpdateElement.update:是否为更新
			 * */
			if (e.update) {
				update.setText("可更新");
			} else {
				update.setText("最新");
			}
			
			if (e.ratio != 100) {
				display.setEnabled(false);
			} else {
				display.setEnabled(true);
			}
			
			//删除按钮点击事件
			remove.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					mOffline.remove(e.cityID);
					updateView();
				}
			});
			
			//查看按钮点击事件
			display.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					/**
					 * public LatLng geoPt:城市中心点坐标
					 * */
					intent.putExtra("x", e.geoPt.longitude);
					intent.putExtra("y", e.geoPt.latitude);
					intent.setClass(OfflineDemo.this, BaseMapDemo.class);
					startActivity(intent);
				}
			});
		}

	}

}


本人基于2017年12月最新API制作。 说明: 1)离线地图不是万能的, 有些依赖在线的功能是无法使用的, 请自行扩展 2)请查看 离线地图示例demo.html 里面的示例,或者查看地图API在线示例: http://developer.baidu.com/map/jsdemo.htm 3) 地图API请查看百度官方说明: http://developer.baidu.com/map/reference/index.php 4)如有更新,请查看网站: http://www.xiaoguo123.com/p/baidumap_offline_v21 5)此API用户大家交流学习,本人没有能力提供太多的技术帮助 6)由于某些用途导致的商业纠纷,和本人无关 新增: 1)支持显示卫星混合地图,瓦片图放到 tiles_hybrid 目录下 2)支持支定义混合图,瓦片图放到 tiles_self 目录下 3)增加根据城市名称设置地图中心, 请自行扩展map_city.js 4)增加鼠标测距示例 5)增加鼠标绘制线面示例 增加新的瓦片图: 1)使用地图下载工具(如太乐地图下载下载你要的地区和级别 2)务必导出瓦片图(百度格式),可以选择导出jpg或png图形 3)按需要修改map_load.js,指定瓦片图的路径,或者按默认的来 4)目录说请看图片: 目录说明.jpg 基本的使用方法如下: 1)加载离线地图必须的文件: [removed][removed] <link rel="stylesheet" type="text/css" href="offlinemap/css/map.css"/> 2)增加一个容器用来显示地图 3)写JS脚本 [removed] var map = new BMap.Map("map_demo"); // 创建Map实例 map.centerAndZoom(new BMap.Point(116.404, 39.915), 7); // 初始化地图,设置中心点坐标和地图级别 map.setCurrentCity("武汉"); // 设置地图中心显示的城市 new! map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放 map.addControl(new BMap.NavigationControl()); //缩放按钮 map.addControl(new BMap.MapTypeControl( {mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP]} )); //添加地图类型控件 离线只支持普通、卫星地图; 三维不支持 [removed]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值