我是靠谱客的博主 愤怒往事,最近开发中收集的这篇文章主要介绍百度地图工具类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述


/**
 * @author liuml
 * @explain
 * @time 2018/1/12 14:59
 */

public interface  BDMapResultInternet {
    /**
     * 地图poi点点击响应回调
     * @param mapPoi poi点对象
     * 名称:mapPoi.getName(); 坐标:mapPoi.getPosition();
     */
    void getClickMapPoiMessage(MapPoi mapPoi);
    /**
     * 地图点击响应回调
     * @param latLng 坐标对象
     */
    void getClickMapMessage(LatLng latLng);
    /**
     * 反地理编码查询结果回调函数
     * @param codeResult 反地理编码查询结果对象
     */
    void getReverseGeoCodeResult(ReverseGeoCodeResult codeResult);
    /**
     * 地理编码查询结果回调函数
     * @param geoCodeResult
     */
    void getGeoCodeResult(GeoCodeResult geoCodeResult);
    /**
     * 定位完成后结果回调
     * @param location
     */
    void getBDLocation(BDLocation location);
    /**
     * poi 详情查询结果回调
     * @param poiDetailResult
     */
    void getPoiDetailResult(PoiDetailResult poiDetailResult);
    /**
     * poi 查询结果回调
     * @param poiResult
     */
    void getPoiResult(PoiResult poiResult);

具体



/**
 * @author liuml
 * @explain 百度地图工具类
 * @time 2018/1/11 19:39
 */
public class BaiduMapUtil implements SensorEventListener, BaiduMap.OnMapClickListener,
        OnGetGeoCoderResultListener, OnGetPoiSearchResultListener {
    private static BaiduMapUtil mInstance;
    private Context mContext;
    private LocationClient mLocationClient = null;

    //回调接口
    private BDMapResultInternet bdMapResult;
    //定位点相关
    boolean isFirstLoc = true; // 是否首次定位
    private boolean locationPointStart = false;
    private MyLocationData locData;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;

    private TextureMapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClientOption.LocationMode tempMode = LocationClientOption.LocationMode.Hight_Accuracy;
    private String tempcoor = "bd09ll";
    private GeoCoder geoCoder;
    private List<PoiInfo> poilist;
    private LatLng point;
    private ReverseGeoCodeOption codeOption;
    private PoiSearch mPoiSearch;

    private BaiduMapUtil() {
    }

    public static synchronized BaiduMapUtil getInstance() {
        if (mInstance == null) {
            mInstance = new BaiduMapUtil();
        }
        return mInstance;
    }


    public BaiduMapUtil init(Context context, TextureMapView mapView,
                             BDMapResultInternet bdMapResult) {
        this.mMapView = mapView;
        this.mBaiduMap = mapView.getMap();
        this.mContext = context;
        this.bdMapResult = bdMapResult;

        BDLocationListener myListener = new MyLocationListener();
        mLocationClient = new LocationClient(context);     //声明LocationClient类
        initLocation();
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        return this;
    }

    /**
     * @return 返回初始化完成后的BaiduMap
     */
    public BaiduMap getBaiduMap() {
        return mBaiduMap;
    }

    /**
     * 设置百度地图响应地图上poi点点击
     */
    public void setMapPoiChickListener() {
        mBaiduMap.setOnMapClickListener(this);
    }

    /**
     * 开始启动定位
     */
    public void locationStart() {
        mBaiduMap.setMyLocationEnabled(true);
        locationPointStart = true;
//        mLocationClient.start();
    }


    /**
     * 初始化百度定位
     */
    private void initLocation() {
        mLocationClient = new LocationClient(mContext.getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
        option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系
        int span = 5000;//5秒定位一次
        option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
        option.setOpenGps(true);//可选,默认false,设置是否使用gps
        option.setLocationNotify(true);//可选,默认false,设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
        option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集
        option.setEnableSimulateGps(true);//可选,默认false,设置是否需要过滤GPS仿真结果,默认需要
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (locationPointStart) {
            double x = sensorEvent.values[SensorManager.DATA_X];
            if (Math.abs(x - lastX) > 1.0) {
                mCurrentDirection = (int) x;
                locData = new MyLocationData.Builder().accuracy(mCurrentAccracy)
                        // 此处设置开发者获取到的方向信息,顺时针0-360
                        .direction(mCurrentDirection).latitude(mCurrentLat)
                        .longitude(mCurrentLon).build();
                mBaiduMap.setMyLocationData(locData);
            }
            lastX = x;
        }
    }

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

    }

    /**
     * poi范围内检索
     *
     * @param latLang      地理范围数据结构,由西南以及东北坐标点确认
     * @param keyWord      检索关键字
     * @param pageCapacity 设置每页容量,默认为每页10条
     * @param pageNum      分页编号
     */
    public void poiSearchInBound(LatLngBounds latLang, String keyWord,
                                 int pageCapacity, int pageNum) {
        PoiBoundSearchOption poiBoundOption = new PoiBoundSearchOption();
        poiBoundOption.bound(latLang);
        poiBoundOption.keyword(keyWord);
        poiBoundOption.pageCapacity(pageCapacity);
        poiBoundOption.pageNum(pageNum);
        mPoiSearch.searchInBound(poiBoundOption);
    }

    /**
     * poi城市内检索
     *
     * @param city         城市名称
     * @param keyWord      检索关键字
     * @param pageCapacity 设置每页容量,默认为每页10条
     * @param pageNum      分页编号
     */
    public void poiSearchInCity(String city, String keyWord, int pageCapacity,
                                int pageNum) {
        PoiCitySearchOption poiCityOption = new PoiCitySearchOption();
        poiCityOption.city(city);
        poiCityOption.keyword(keyWord);
        poiCityOption.pageCapacity(pageCapacity);
        poiCityOption.pageNum(pageNum);
        mPoiSearch.searchInCity(poiCityOption);
    }

    /**
     * poi周边检索
     *
     * @param keyWord      检索关键字
     * @param location     检索位置
     * @param pageCapacity 设置每页容量,默认为每页10条
     * @param pageNum      分页编号
     * @param radius       设置检索的半径范围
     * @param sortType     搜索结果排序规则,可选,默认
     */
    public void pioSearchNearby(String keyWord, LatLng location,
                                int pageCapacity, int pageNum, int radius, PoiSortType sortType) {
        PoiNearbySearchOption poiNearbyOption = new PoiNearbySearchOption();
        poiNearbyOption.keyword(keyWord);
        poiNearbyOption.location(location);
        poiNearbyOption.pageCapacity(pageCapacity);
        poiNearbyOption.pageNum(pageNum);
        poiNearbyOption.radius(radius);
        poiNearbyOption.sortType(sortType);
    }

    /**
     * 手动定位当前位置
     */
    public void Location() {
        // 开启定位
        mLocationClient.start();
        // start之后会默认发起一次定位请求,开发者无须判断isstart并主动调用request
        mLocationClient.requestLocation();
    }

    /**
     * 手动获取附近poi点
     */
    public void getlocationPlacePoi() {
        codeOption.location(point);
        geoCoder.reverseGeoCode(codeOption);
    }

    public  void stopLocation(){
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }
    /**
     * 释放百度地图(Activity onDestroy调用方法)
     */
    public void onDestroyBDMap() {
        isFirstLoc = true;
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        if (geoCoder != null) {
            geoCoder.destroy();
        }
        if (mPoiSearch != null) {
            mPoiSearch.destroy();
        }


        // 退出时销毁定位
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        // 关闭定位图层
        if (mBaiduMap != null) {
            mBaiduMap.setMyLocationEnabled(false);
        }
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;

        }
    }

    /**
     * Activity onResume调用方法
     */
    public void onResumeBDMap() {
        mMapView.onResume();
    }

    /**
     * Activity onPause调用方法
     */
    public void onPauseBDMap() {
        mMapView.onPause();
    }

    /**
     * 定位完成后结果回调
     */
    class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            bdMapResult.getBDLocation(location);
            point = new LatLng(location.getLatitude(), location.getLongitude());

            //Receive Location
            StringBuilder sb = new StringBuilder(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("nerror code : ");
            sb.append(location.getLocType());
            sb.append("nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("nradius : ");
            sb.append(location.getRadius());

            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("nspeed : ");
                sb.append(location.getSpeed());// 单位:公里每小时
                sb.append("nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("nheight : ");
                sb.append(location.getAltitude());// 单位:米
                sb.append("ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("naddr : ");
                sb.append(location.getAddrStr());
                sb.append("ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("noperationers : ");
                sb.append(location.getOperators());
                sb.append("ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("ndescribe : ");
                sb.append("离线定位成功,离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("ndescribe : ");
                sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("ndescribe : ");
                sb.append("网络不同导致定位失败,请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
            }
            sb.append("nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息

            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("npoi= : ");
                    sb.append(p.getId()).append(" ").append(p.getName()).append(" ").append(p.getRank());
                }
            }
//            LogUtil.d("BaiduMapUtil","n"+sb);
            if (locationPointStart) {
                startMyLocation(location);
            }
        }
    }


    /**
     * 地理编码查询结果回调函数
     */
    @Override
    public void onGetGeoCodeResult(GeoCodeResult arg0) {
        // TODO Auto-generated method stub
        bdMapResult.getGeoCodeResult(arg0);
    }

    /**
     * 反地理编码查询结果回调函数
     */
    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
        bdMapResult.getReverseGeoCodeResult(arg0);
    }

    /**
     * 地图点击响应回调
     */
    @Override
    public void onMapClick(LatLng arg0) {
        // TODO Auto-generated method stub
        bdMapResult.getClickMapMessage(arg0);
    }


    /**
     * poi 详情查询结果回调
     */
    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        // TODO Auto-generated method stub
        bdMapResult.getPoiDetailResult(poiDetailResult);
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    /**
     * poi 查询结果回调
     */
    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        // TODO Auto-generated method stub
        bdMapResult.getPoiResult(poiResult);
    }

    /**
     * 地图poi点点击响应回调
     */
    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        // TODO Auto-generated method stub
        // mapPoi.getName(); // 名称
        // mapPoi.getPosition(); // 坐标
        bdMapResult.getClickMapPoiMessage(mapPoi);
        return false;
    }

    public void startMyLocation(BDLocation location) {
        mCurrentLat = location.getLatitude();
        mCurrentLon = location.getLongitude();
        mCurrentAccracy = location.getRadius();

        locData = new MyLocationData.Builder()
                .accuracy(0)
                // 此处设置开发者获取到的方向信息,顺时针0-360
                .direction(mCurrentDirection)
                .latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        mBaiduMap.setMyLocationData(locData);


        // 设置定位图层的配置(定位模式,是否允许方向信息,用户自定义定位图标)
//        MyLocationConfiguration.LocationMode following = MyLocationConfiguration.LocationMode.FOLLOWING;//定位跟随态
//        MyLocationConfiguration config = new MyLocationConfiguration(following, true, mCurrentMarker);
//        mBaiduMap.setMyLocationConfiguration(config);

        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory
                    .newMapStatus(builder.build()));
        }
    }
}

仅仅获取当前位置工具类

package com.sinochem.www.car.owner.utils.map;

/**
 * Created by liuml on 2020/7/22 14:59
 */

import android.app.Activity;
import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

/**
 * 仅用于获取经纬度
 */
public class BaiduMapLocateUtil {

    public interface OnLocateCompletedListener {
        /**
         * 除了经纬度以外,如果还需要其他定位信息,可以从location参数获取
         */
        void onLocateCompleted(double latitude, double longitude, BDLocation location);
    }

    private OnLocateCompletedListener mOnLocateCompletedListener;
    private LocationClient mBDLocationClient;
    private BDLocationListener mBDLocationListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //获取定位结果
            if (mOnLocateCompletedListener != null) {
                mOnLocateCompletedListener.onLocateCompleted(
                        location.getLatitude(),
                        location.getLongitude(),
                        location);
            }
            mBDLocationClient.stop();
        }

    };

    private BaiduMapLocateUtil(Context context, OnLocateCompletedListener locateListener) {
        mOnLocateCompletedListener = locateListener;
        mBDLocationClient = new LocationClient(context.getApplicationContext());
        mBDLocationClient.registerLocationListener(mBDLocationListener);
        initLocation();
        mBDLocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();

        //可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);

        //可选,默认gcj02,设置返回的定位结果坐标系
        option.setCoorType("bd09ll");

        //可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
        int span = 0;
        option.setScanSpan(span);

        //可选,设置是否需要地址信息,默认不需要
        option.setIsNeedAddress(true);

        //可选,默认false,设置是否使用gps
        option.setOpenGps(true);

        //可选,默认false,设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setLocationNotify(true);

        //可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
        option.setIsNeedLocationDescribe(true);

        //可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
        option.setIsNeedLocationPoiList(true);

        //可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
        option.setIgnoreKillProcess(false);

        //可选,默认false,设置是否收集CRASH信息,默认收集
        option.SetIgnoreCacheException(false);

        //可选,默认false,设置是否需要过滤GPS仿真结果,默认需要
        option.setEnableSimulateGps(false);

        mBDLocationClient.setLocOption(option);
    }

    public static void locate(Activity activity, OnLocateCompletedListener locateListener) {
        new BaiduMapLocateUtil(activity, locateListener);
    }
}

使用:

BaiduMapLocateUtil.locate(this, new BaiduMapLocateUtil.OnLocateCompletedListener() {

            @Override
            public void onLocateCompleted(double latitude, double longitude, BDLocation location) {
                StringBuilder result = new StringBuilder();
                result.append("latitude: ").append(latitude).append("n");
                result.append("longitude: ").append(longitude).append("n");
                result.append("city: ").append(location.getCity()).append("n");
                Log.d("BaiduLocationApiDem", result.toString());
                visitfreqStations(String.valueOf(latitude), String.valueOf(longitude));
            }
        });

最后

以上就是愤怒往事为你收集整理的百度地图工具类的全部内容,希望文章能够帮你解决百度地图工具类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部