Android百度地图(四)如何引入离线地图包

Android百度地图(四)如何引入离线地图包

本文代码在http://blog.csdn.net/xyzz609/article/details/51955363的基础上进一步修改,有兴趣的同学可以研究下怎么修改的

本篇我们准备为地图添加:引入离线地图包

本文参考的是http://blog.csdn.net/lmj623565791/article/details/37758097
官方文档:http://lbsyun.baidu.com/index.php?title=androidsdk/guide/offlinemap

没有例子我只能摸虾,

开发者可参考官方提供demo工程中的OfflineDemo 文件

我是没有找到,找到的给我回复下吧

开始导入离线包

新增的文件目录看看你是这么写的吗

Android百度地图(四)如何引入离线地图包_第1张图片

本文参考大神:http://blog.csdn.net/lmj623565791/article/details/37758097

其实说实话,我最后实现点击下载啥的,看见济南市了吧哈哈

但是,我有点疑问,不能删除,还有下载哪里了,为什么我断网之后,不能显示济南地图呢。。。

不管了,不过效果是出来了,

Android百度地图(四)如何引入离线地图包_第2张图片

布局文件:activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <com.baidu.mapapi.map.MapView
        android:id="@+id/id_bmapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true" />

    <RelativeLayout
        android:id="@+id/id_marker_info"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="220dp"
        android:layout_alignParentBottom="true"
        android:background="#CC4e5a6b"
        android:clickable="true" >

        <ImageView
            android:id="@+id/info_img"
            android:layout_width="fill_parent"
            android:layout_height="150dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            android:layout_marginTop="10dp"
            android:alpha="1.0"
            android:background="@drawable/map_image_border_white"
            android:clickable="true"
            android:scaleType="fitXY"
            android:src="@mipmap/a04" />

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:layout_alignParentBottom="true"
            android:background="@drawable/bg_map_bottom" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/info_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="老米家泡馍小炒"
                    android:textColor="#FFF5EB" />

                <TextView
                    android:id="@+id/info_distance"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="距离200米"
                    android:textColor="#FFF5EB" />
            LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="20dp"
                android:orientation="horizontal" >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="zan"
                    android:src="@drawable/map_zan" />

                <TextView
                    android:id="@+id/info_zan"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="652"
                    android:textColor="#FFF5EB" />
            LinearLayout>
        RelativeLayout>
    RelativeLayout>

RelativeLayout>

展示视图控制文件:MainActivity

package com.yang.baidumapceshi;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.yang.baidumapceshi.MyOrientationListener.OnOrientationListener;

import java.lang.reflect.Method;
import java.util.List;

public class MainActivity extends Activity
{
    /**
     * 地图控件
     */
    private MapView mMapView = null;
    /**
     * 地图实例
     */
    private BaiduMap mBaiduMap;
    /**
     * 定位的客户端
     */
    private LocationClient mLocationClient;
    /**
     * 定位的监听器
     */
    public MyLocationListener mMyLocationListener;
    /**
     * 当前定位的模式
     */
    private LocationMode mCurrentMode = LocationMode.NORMAL;
    /***
     * 是否是第一次定位
     */
    private volatile boolean isFristLocation = true;

    /**
     * 最新一次的经纬度
     */
    private double mCurrentLantitude;
    private double mCurrentLongitude;
    /**
     * 当前的精度
     */
    private float mCurrentAccracy;
    /**
     * 方向传感器的监听器
     */
    private MyOrientationListener myOrientationListener;
    /**
     * 方向传感器X方向的值
     */
    private int mXDirection;

    /**
     * 地图定位的模式
     */
    private String[] mStyles = new String[] { "地图模式【正常】", "地图模式【跟随】",
            "地图模式【罗盘】" };
    private int mCurrentStyle = 0;
    // 初始化全局 bitmap 信息,不用时及时 recycle
    private BitmapDescriptor mIconMaker;
    /**
     * 详细信息的 布局
     */
    private RelativeLayout mMarkerInfoLy;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        // 第一次定位
        isFristLocation = true;
        // 获取地图控件引用
        mMapView = (MapView) findViewById(R.id.id_bmapView);
        mMarkerInfoLy = (RelativeLayout) findViewById(R.id.id_marker_info);
        // 获得地图的实例
        mBaiduMap = mMapView.getMap();
        mIconMaker = BitmapDescriptorFactory.fromResource(R.mipmap.maker);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(msu);
        // 初始化定位
        initMyLocation();
        // 初始化传感器
        initOritationListener();
        initMarkerClickEvent();
        initMapClickEvent();

    }
    private void initMapClickEvent()
    {
            mBaiduMap.setOnMapClickListener(new OnMapClickListener()
        {

            @Override
            public boolean onMapPoiClick(MapPoi arg0)
            {
                return false;
            }

            @Override
            public void onMapClick(LatLng arg0)
            {
                mMarkerInfoLy.setVisibility(View.GONE);
                mBaiduMap.hideInfoWindow();

            }
        });
    }

    private void initMarkerClickEvent()
    {
        // 对Marker的点击
        mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener()
        {
            @Override
            public boolean onMarkerClick(final Marker marker)
            {
                // 获得marker中的数据
                Info info = (Info) marker.getExtraInfo().get("info");

                InfoWindow mInfoWindow;
                // 生成一个TextView用户在地图中显示InfoWindow
                TextView location = new TextView(getApplicationContext());
                location.setBackgroundResource(R.mipmap.location_tips);
                location.setPadding(30, 20, 30, 50);
                location.setText(info.getName());
                // 将marker所在的经纬度的信息转化成屏幕上的坐标
                final LatLng ll = marker.getPosition();
                Point p = mBaiduMap.getProjection().toScreenLocation(ll);
                p.y -= 47;
                LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
                //创建InfoWindow , 传入 view, 地理坐标, y 轴偏移量
               mInfoWindow = new InfoWindow(location, llInfo, p.y);
                // 显示InfoWindow
                mBaiduMap.showInfoWindow(mInfoWindow);
                // 设置详细信息布局为可见
                mMarkerInfoLy.setVisibility(View.VISIBLE);
                // 根据商家信息为详细信息布局设置信息
                popupInfo(mMarkerInfoLy, info);
                return true;
            }
        });
    }
    /**
     * 根据info为布局上的控件设置信息
     *
     */
    protected void popupInfo(RelativeLayout mMarkerLy, Info info)
    {
        ViewHolder viewHolder = null;
        if (mMarkerLy.getTag() == null)
        {
            viewHolder = new ViewHolder();
            viewHolder.infoImg = (ImageView) mMarkerLy
                    .findViewById(R.id.info_img);
            viewHolder.infoName = (TextView) mMarkerLy
                    .findViewById(R.id.info_name);
            viewHolder.infoDistance = (TextView) mMarkerLy
                    .findViewById(R.id.info_distance);
            viewHolder.infoZan = (TextView) mMarkerLy
                    .findViewById(R.id.info_zan);

            mMarkerLy.setTag(viewHolder);
        }
        viewHolder = (ViewHolder) mMarkerLy.getTag();
        viewHolder.infoImg.setImageResource(info.getImgId());
        viewHolder.infoDistance.setText(info.getDistance());
        viewHolder.infoName.setText(info.getName());
        viewHolder.infoZan.setText(info.getZan() + "");
    }


    /**
     * 复用弹出面板mMarkerLy的控件
     *
     */
    private class ViewHolder
    {
        ImageView infoImg;
        TextView infoName;
        TextView infoDistance;
        TextView infoZan;
    }

    /**
     * 初始化方向传感器
     */
    private void initOritationListener()
    {
        myOrientationListener = new MyOrientationListener(
                getApplicationContext());
        myOrientationListener
                .setOnOrientationListener(new OnOrientationListener()
                {
                    @Override
                    public void onOrientationChanged(float x)
                    {
                        mXDirection = (int) x;

                        // 构造定位数据
                        MyLocationData locData = new MyLocationData.Builder()
                                .accuracy(mCurrentAccracy)
                                // 此处设置开发者获取到的方向信息,顺时针0-360
                                .direction(mXDirection)
                                .latitude(mCurrentLantitude)
                                .longitude(mCurrentLongitude).build();
                        // 设置定位数据
                        mBaiduMap.setMyLocationData(locData);
                        // 设置自定义图标
                        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                                .fromResource(R.mipmap.navi_map_gps_locked);
                        MyLocationConfiguration config = new MyLocationConfiguration(
                                mCurrentMode, true, mCurrentMarker);
                        mBaiduMap.setMyLocationConfigeration(config);

                    }
                });
    }

    /**
     * 初始化定位相关代码
     */
    private void initMyLocation()
    {
        // 定位初始化
        mLocationClient = new LocationClient(this);
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);
        // 设置定位的相关配置
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
    }

    /**
     * 初始化图层
     */
    public void addInfosOverlay(List infos)
    {
        mBaiduMap.clear();
        LatLng latLng = null;
        OverlayOptions overlayOptions = null;
        Marker marker = null;
        for (Info info : infos)
        {
            // 位置
            latLng = new LatLng(info.getLatitude(), info.getLongitude());
            // 图标
            overlayOptions = new MarkerOptions().position(latLng)
                    .icon(mIconMaker).zIndex(5);
            marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
            Bundle bundle = new Bundle();
            bundle.putSerializable("info", info);
            marker.setExtraInfo(bundle);
        }
        // 将地图移到到最后一个经纬度位置
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.setMapStatus(u);
    }

    /**
     * 实现实位回调监听
     */
    public class MyLocationListener implements BDLocationListener
    {
        @Override
        public void onReceiveLocation(BDLocation location)
        {

            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息,顺时针0-360
                    .direction(mXDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mCurrentAccracy = location.getRadius();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            mCurrentLantitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();
            // 设置自定义图标
            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                    .fromResource(R.mipmap.navi_map_gps_locked);
            MyLocationConfiguration config = new MyLocationConfiguration(
                    mCurrentMode, true, mCurrentMarker);
            mBaiduMap.setMyLocationConfigeration(config);
            // 第一次定位时,将地图位置移动到当前位置
            if (isFristLocation)
            {
                isFristLocation = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 默认点击menu菜单,菜单项不现实图标,反射强制其显示
     */
    @Override
    public boolean onMenuOpened(int featureId, Menu menu)
    {

        if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null)
        {
            if (menu.getClass().getSimpleName().equals("MenuBuilder"))
            {
                try
                {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e)
                {
                }
            }

        }
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {

        switch (item.getItemId())
        {
            case R.id.id_menu_map_addMaker:
                addInfosOverlay(Info.infos);
                break;
            case R.id.id_menu_map_common:
                // 普通地图
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                break;
            case R.id.id_menu_map_site:// 卫星地图
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.id_menu_map_traffic:
                // 开启交通图

                if (mBaiduMap.isTrafficEnabled())
                {
                    item.setTitle("开启实时交通");
                    mBaiduMap.setTrafficEnabled(false);
                } else
                {
                    item.setTitle("关闭实时交通");
                    mBaiduMap.setTrafficEnabled(true);
                }
                break;
            case R.id.id_menu_map_myLoc:
                center2myLoc();
                break;
            //离线地图
            case R.id.id_menu_map_offline:
                Intent intent = new Intent(MainActivity.this, OfflineMapActivity.class);
                startActivity(intent);
                break;
            case R.id.id_menu_map_style:
                mCurrentStyle = (++mCurrentStyle) % mStyles.length;
                item.setTitle(mStyles[mCurrentStyle]);
                // 设置自定义图标
                switch (mCurrentStyle)
                {
                    case 0:
                        mCurrentMode = LocationMode.NORMAL;
                        break;
                    case 1:
                        mCurrentMode = LocationMode.FOLLOWING;
                        break;
                    case 2:
                        mCurrentMode = LocationMode.COMPASS;
                        break;
                }
                BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                        .fromResource(R.mipmap.navi_map_gps_locked);
                MyLocationConfiguration config = new MyLocationConfiguration(
                        mCurrentMode, true, mCurrentMarker);
                mBaiduMap.setMyLocationConfigeration(config);
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 地图移动到我的位置,此处可以重新发定位请求,然后定位;
     * 直接拿最近一次经纬度,如果长时间没有定位成功,可能会显示效果不好
     */
    private void center2myLoc()
    {
        LatLng ll = new LatLng(mCurrentLantitude, mCurrentLongitude);
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.animateMapStatus(u);
    }

    @Override
    protected void onStart()
    {
        // 开启图层定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted())
        {
            mLocationClient.start();
        }
        // 开启方向传感器
        myOrientationListener.start();
        super.onStart();
    }

    @Override
    protected void onStop()
    {
        // 关闭图层定位
        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();

        // 关闭方向传感器
        myOrientationListener.stop();
        super.onStop();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        // 在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
        mMapView.onDestroy();
        mIconMaker.recycle();
        mMapView = null;
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
        mMapView.onPause();
    }

}

Info

package com.yang.baidumapceshi;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yang_zzheng on 2016/7/19
 * [email protected]
 */
public class Info implements Serializable
{
    private static final long serialVersionUID = -758459502806858414L;
    /**
     * 精度
     */
    private double latitude;
    /**
     * 纬度
     */
    private double longitude;
    /**
     * 图片ID,真实项目中可能是图片路径
     */
    private int imgId;
    /**
     * 商家名称
     */
    private String name;
    /**
     * 距离
     */
    private String distance;
    /**
     * 赞数量
     */
    private int zan;

    public static List infos = new ArrayList();

    static
    {
        infos.add(new Info(34.242652, 108.971171, R.mipmap.a01, "英伦贵族小旅馆",
                "距离209米", 1456));
        infos.add(new Info(34.242952, 108.972171, R.mipmap.a02, "沙井国际洗浴会所",
                "距离897米", 456));
        infos.add(new Info(34.242852, 108.973171, R.mipmap.a03, "五环服装城",
                "距离249米", 1456));
        infos.add(new Info(34.242152, 108.971971, R.mipmap.a04, "老米家泡馍小炒",
                "距离679米", 1456));
    }

    public Info()
    {
    }

    public Info(double latitude, double longitude, int imgId, String name,
                String distance, int zan)
    {
        super();
        this.latitude = latitude;
        this.longitude = longitude;
        this.imgId = imgId;
        this.name = name;
        this.distance = distance;
        this.zan = zan;
    }

    public double getLatitude()
    {
        return latitude;
    }

    public void setLatitude(double latitude)
    {
        this.latitude = latitude;
    }

    public double getLongitude()
    {
        return longitude;
    }

    public void setLongitude(double longitude)
    {
        this.longitude = longitude;
    }

    public String getName()
    {
        return name;
    }

    public int getImgId()
    {
        return imgId;
    }

    public void setImgId(int imgId)
    {
        this.imgId = imgId;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getDistance()
    {
        return distance;
    }

    public void setDistance(String distance)
    {
        this.distance = distance;
    }

    public int getZan()
    {
        return zan;
    }

    public void setZan(int zan)
    {
        this.zan = zan;
    }

}

MyOrientationListener

package com.yang.baidumapceshi;

/**
 * Created by yang_zzheng on 2016/7/18
 * [email protected]
 */
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class MyOrientationListener implements SensorEventListener
{

    private Context context;
    private SensorManager sensorManager;
    private Sensor sensor;

    private float lastX ;

    private OnOrientationListener onOrientationListener ;

    public MyOrientationListener(Context context)
    {
        this.context = context;
    }

    // 开始
    public void start()
    {
        // 获得传感器管理器
        sensorManager = (SensorManager) context
                .getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null)
        {
            // 获得方向传感器
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        }
        // 注册
        if (sensor != null)
        {//SensorManager.SENSOR_DELAY_UI
            sensorManager.registerListener(this, sensor,
                    SensorManager.SENSOR_DELAY_UI);
        }

    }

    // 停止检测
    public void stop()
    {
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {

    }

    @Override
    public void onSensorChanged(SensorEvent event)
    {
        // 接受方向感应器的类型
        if (event.sensor.getType() == Sensor.TYPE_ORIENTATION)
        {
            // 这里我们可以得到数据,然后根据需要来处理
            float x = event.values[SensorManager.DATA_X];

            if( Math.abs(x- lastX) > 1.0 )
            {
                onOrientationListener.onOrientationChanged(x);
            }
//            Log.e("DATA_X", x+"");
            lastX = x ;

        }
    }

    public void setOnOrientationListener(OnOrientationListener onOrientationListener)
    {
        this.onOrientationListener = onOrientationListener ;
    }


    public interface OnOrientationListener
    {
        void onOrientationChanged(float x);
    }

}

OfflineMapActivity

package com.yang.baidumapceshi;

/**
 * Created by yang_zzheng on 2016/7/19
 * [email protected]
 */

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.yang.baidumapceshi.OfflineMapCityBean.Flag;

import java.util.ArrayList;
import java.util.List;

public class OfflineMapActivity extends Activity
{

    protected static final String TAG = "OfflineMapActivity";
    /**
     * 离线地图功能
     */
    private MKOfflineMap mOfflineMap;
    private ListView mListView;
    /**
     * 离线地图的数据
     */
    private List mDatas = new ArrayList();
    /**
     * 适配器
     */
    private MyOfflineCityBeanAdapter mAdapter;
    private LayoutInflater mInflater;
    private Context context;
    /**
     * 目前加入下载队列的城市
     */
    private List mCityCodes = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.offlinemap);

        context = this;
        mInflater = LayoutInflater.from(this);
        /**
         * 初始化离线地图
         */
        initOfflineMap();
        /**
         * 初始化ListView数据
         */
        initData();
        /**
         * 初始化ListView
         */
        initListView();

    }

    private void initListView()
    {
        mListView = (ListView) findViewById(R.id.id_offline_map_lv);
        mAdapter = new MyOfflineCityBeanAdapter();
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView parent, View view,
                                    int position, long id)
            {
                int cityId = mDatas.get(position).getCityCode();
                if (mCityCodes.contains(cityId))
                {
                    removeTaskFromQueue(position, cityId);
                } else
                {
                    addToDownloadQueue(position, cityId);
                }

            }
        });
    }

    /**
     * 将任务移除下载队列
     *
     * @param pos
     * @param cityId
     */
    public void removeTaskFromQueue(int pos, int cityId)
    {
        mOfflineMap.pause(cityId);
        mDatas.get(pos).setFlag(Flag.NO_STATUS);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 将下载任务添加至下载队列
     *
     * @param pos
     * @param cityId
     */
    public void addToDownloadQueue(int pos, int cityId)
    {
        mCityCodes.add(cityId);
        mOfflineMap.start(cityId);
        mDatas.get(pos).setFlag(Flag.PAUSE);
        mAdapter.notifyDataSetChanged();
    }

    private void initData()
    {

        // 获得所有热门城市
        ArrayList offlineCityList = mOfflineMap
                .getHotCityList();
        // 手动添加了济南
        MKOLSearchRecord xian = new MKOLSearchRecord();
        xian.cityID = 289;
        xian.cityName = "济南市";
        offlineCityList.add(xian);
        // 获得所有已经下载的城市列表
        ArrayList allUpdateInfo = mOfflineMap.getAllUpdateInfo();
        // 设置所有数据的状态
        for (MKOLSearchRecord record : offlineCityList)
        {
            OfflineMapCityBean cityBean = new OfflineMapCityBean();
            cityBean.setCityName(record.cityName);
            cityBean.setCityCode(record.cityID);

            if (allUpdateInfo != null)//没有任何下载记录,返回null,为啥不返回空列表~~
            {
                for (MKOLUpdateElement ele : allUpdateInfo)
                {
                    if (ele.cityID == record.cityID)
                    {
                        cityBean.setProgress(ele.ratio);
                    }
                }

            }
            mDatas.add(cityBean);
        }

    }

    /**
     * 初始化离线地图
     */
    private void initOfflineMap()
    {
        mOfflineMap = new MKOfflineMap();
        // 设置监听
        mOfflineMap.init(new MKOfflineMapListener()
        {
            @Override
            public void onGetOfflineMapState(int type, int state)
            {
                switch (type)
                {
                    case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
                        // 离线地图下载更新事件类型
                        MKOLUpdateElement update = mOfflineMap.getUpdateInfo(state);
                        Log.e(TAG, update.cityName + " ," + update.ratio);
                        for (OfflineMapCityBean bean : mDatas)
                        {
                            if (bean.getCityCode() == state)
                            {
                                bean.setProgress(update.ratio);
                                bean.setFlag(Flag.DOWNLOADING);
                                break;
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                        Log.e(TAG, "TYPE_DOWNLOAD_UPDATE");
                        break;
                    case MKOfflineMap.TYPE_NEW_OFFLINE:
                        // 有新离线地图安装
                        Log.e(TAG, "TYPE_NEW_OFFLINE");
                        break;
                    case MKOfflineMap.TYPE_VER_UPDATE:
                        // 版本更新提示
                        break;
                }

            }
        });
    }

    @Override
    protected void onDestroy()
    {
        mOfflineMap.destroy();
        super.onDestroy();
    }

    /**
     * 热门城市地图列表的Adapter
     *
     * @author zhy
     *
     */
    class MyOfflineCityBeanAdapter extends BaseAdapter
    {

        @Override
        public boolean isEnabled(int position)
        {
            if (mDatas.get(position).getProgress() == 100)
            {
                return false;
            }
            return super.isEnabled(position);
        }

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

        @Override
        public Object getItem(int position)
        {
            return mDatas.get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            OfflineMapCityBean bean = mDatas.get(position);
            ViewHolder holder = null;
            if (convertView == null)
            {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.offlinemap_item,
                        parent, false);
                holder.cityName = (TextView) convertView
                        .findViewById(R.id.id_cityname);
                holder.progress = (TextView) convertView
                        .findViewById(R.id.id_progress);
                convertView.setTag(holder);
            } else
            {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.cityName.setText(bean.getCityName());
            int progress = bean.getProgress();
            String progressMsg = "";
            // 根据进度情况,设置显示
            if (progress == 0)
            {
                progressMsg = "未下载";
            } else if (progress == 100)
            {
                bean.setFlag(Flag.NO_STATUS);
                progressMsg = "已下载";
            } else
            {
                progressMsg = progress + "%";
            }
            // 根据当前状态,设置显示
            switch (bean.getFlag())
            {
                case PAUSE:
                    progressMsg += "【等待下载】";
                    break;
                case DOWNLOADING:
                    progressMsg += "【正在下载】";
                    break;
                default:
                    break;
            }
            holder.progress.setText(progressMsg);
            return convertView;
        }

        private class ViewHolder
        {
            TextView cityName;
            TextView progress;

        }
    }
}

OfflineMapCityBean

package com.yang.baidumapceshi;

/**
 * Created by yang_zzheng on 2016/7/19
 * [email protected]
 */
public class OfflineMapCityBean
{
    private String cityName;
    private int cityCode;
    /**
     * 下载的进度
     */
    private int progress;

    private Flag flag = Flag.NO_STATUS;
    /**
     * 下载的状态:无状态,暂停,正在下载
     *
     */
    public enum Flag
    {
        NO_STATUS,PAUSE,DOWNLOADING
    }

    public Flag getFlag()
    {
        return flag;
    }

    public void setFlag(Flag flag)
    {
        this.flag = flag;
    }

    public OfflineMapCityBean()
    {
    }

    public OfflineMapCityBean(String cityName, int cityCode, int progress)
    {
        this.cityName = cityName;
        this.cityCode = cityCode;
        this.progress = progress;
    }

    public String getCityName()
    {
        return cityName;
    }

    public void setCityName(String cityName)
    {
        this.cityName = cityName;
    }

    public int getCityCode()
    {
        return cityCode;
    }

    public void setCityCode(int cityCode)
    {
        this.cityCode = cityCode;
    }

    public int getProgress()
    {
        return progress;
    }

    public void setProgress(int progress)
    {
        this.progress = progress;
    }

}

offlinemap.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

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

RelativeLayout>

offlinemap_item.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@mipmap/listbg_normal" >

    <TextView
        android:id="@+id/id_cityname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="8dp"
        android:text="合肥"
        android:textColor="#ff000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/id_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="8dp"
        android:text="已完成"
        android:textColor="#ff000000"
        android:textSize="18sp" />

RelativeLayout>

main.xml

"http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/id_menu_map_common"
        android:icon="@mipmap/ic_icon_dog"
        app:showAsAction="never"
        android:title="普通地图"/>
    <item
        android:id="@+id/id_menu_map_site"
        android:icon="@mipmap/ic_icon_dog"
        app:showAsAction="never"
        android:title="卫星地图"/>
    <item
        android:id="@+id/id_menu_map_traffic"
        android:icon="@mipmap/ic_icon_dog"
        app:showAsAction="never"
        android:title="开启实时交通"/>
    <item
        android:id="@+id/id_menu_map_myLoc"
        android:icon="@mipmap/ic_icon_dog"
        app:showAsAction="never"
        android:title="我的位置"/>
    <item
        android:id="@+id/id_menu_map_addMaker"
        android:icon="@mipmap/ic_icon_dog"
        app:showAsAction="never"
        android:title="添加覆盖物"/>
    <item
        android:id="@+id/id_menu_map_style"
        android:icon="@mipmap/ic_icon_dog"
        app:showAsAction="never"
        android:title="地图模式【正常】"/>
    <item
        android:id="@+id/id_menu_map_offline"
        android:icon="@mipmap/ic_icon_dog"
        app:showAsAction="never"
        android:title="下载离线地图"/>

map_image_border_white.xml


<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <stroke
        android:width="2dp"
        android:color="#AAffffff" />

    <padding
        android:bottom="2dp"
        android:left="2dp"
        android:right="2dp"
        android:top="2dp" />

shape>

我这个人比较实在,你照着copy很快就能实现

喜欢的就给赞吧,不喜欢的勿喷,有的地方copy多了,哈哈,我写是照着学习,勿怪。

代码下载

本文中的代码已经在文中全部出现过了,为什么还需要一个下载币呢,是因为我的下载币不够用了额,下载其他大神的代码,需要,所以请赞助一下吧。当然你不想赞助的话,你可以在文章中一个一个的copy,绝对的一模一样,绝对的开源,赞助一个下载币吧

里面附带这各个城市的cityCode

http://download.csdn.net/detail/xyzz609/9580638

你可能感兴趣的:(百度地图,android,百度地图,地图,文档,91)