首页 > 学院 > 开发设计 > 正文

百度地图个人demo

2019-11-09 18:21:10
字体:
来源:转载
供稿:网友
LocationService.java
package example.com.baidumaptest;/** * Created by cherish on 2017/2/6. */import com.baidu.location.BDLocationListener;import com.baidu.location.LocationClient;import com.baidu.location.LocationClientOption;import com.baidu.location.LocationClientOption.LocationMode;import android.content.Context;/** * * @author baidu * */public class LocationService {    PRivate LocationClient client = null;    private LocationClientOption mOption,DIYoption;    private Object  objLock = new Object();    /***     *     * @param locationContext     */    public LocationService(Context locationContext){        synchronized (objLock) {            if(client == null){                client = new LocationClient(locationContext);                client.setLocOption(getDefaultLocationClientOption());            }        }    }    /***     *     * @param listener     * @return     */    public boolean registerListener(BDLocationListener listener){        boolean isSuccess = false;        if(listener != null){            client.registerLocationListener(listener);            isSuccess = true;        }        return  isSuccess;    }    public void unregisterListener(BDLocationListener listener){        if(listener != null){            client.unRegisterLocationListener(listener);        }    }    /***     *     * @param option     * @return isSuccessSetOption     */    public boolean setLocationOption(LocationClientOption option){        boolean isSuccess = false;        if(option != null){            if(client.isStarted())                client.stop();            DIYoption = option;            client.setLocOption(option);            isSuccess = true;        }        return isSuccess;    }    public LocationClientOption getOption(){        return DIYoption;    }    /***     *     * @return DefaultLocationClientOption     */    public LocationClientOption getDefaultLocationClientOption(){        if(mOption == null){            mOption = new LocationClientOption();            mOption.setLocationMode(LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备            mOption.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll;            mOption.setScanSpan(10000);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的            mOption.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要            mOption.setIsNeedLocationDescribe(true);//可选,设置是否需要地址描述            mOption.setNeedDeviceDirect(false);//可选,设置是否需要设备方向结果            mOption.setLocationNotify(false);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果            mOption.setIgnoreKillProcess(true);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死            mOption.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”            mOption.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到            mOption.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集            mOption.setIsNeedAltitude(false);//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用        }        return mOption;    }    public void start(){        synchronized (objLock) {            if(client != null && !client.isStarted()){                client.start();            }        }    }    public void stop(){        synchronized (objLock) {            if(client != null && client.isStarted()){                client.stop();            }        }    }}
MainActivity.java
package example.com.baidumaptest;import android.Manifest;import android.annotation.TargetApi;import android.app.Activity;import android.content.pm.PackageManager;import android.os.Build;import android.os.Bundle;import android.util.Log;import com.baidu.mapapi.SDKInitializer;import com.baidu.mapapi.map.BaiduMap;import com.baidu.mapapi.map.MapPoi;import com.baidu.mapapi.map.MapStatusUpdate;import com.baidu.mapapi.map.MapStatusUpdateFactory;import com.baidu.mapapi.map.TextureMapView;import com.baidu.location.BDLocationListener;import com.baidu.mapapi.model.LatLng;import java.util.ArrayList;public class MainActivity extends Activity {    private TextureMapView mMapView = null;    public BDLocationListener myListener = new MyLocationListener();    public LocationService locationService;    public static BaiduMap baiduMap;    public static MapStatusUpdate msu;    private final int SDK_PERMISSION_REQUEST = 127;    private String permissionInfo;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        SDKInitializer.initialize(getapplicationContext());        setContentView(R.layout.activity_main);        mMapView = (TextureMapView) findViewById(R.id.bmapView);        locationService = new LocationService(getApplicationContext());        locationService.registerListener(myListener); //注册监听函数        baiduMap = mMapView.getMap();        getPersimmions();        baiduMap.setMyLocationEnabled(true);//开启定位图层        msu = MapStatusUpdateFactory.zoomTo(18);        baiduMap.animateMapStatus(msu);        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {            @Override            public void onMapClick(LatLng latLng) {                Log.e("onClick",latLng.latitude+","+latLng.longitude);            }            @Override            public boolean onMapPoiClick(MapPoi mapPoi) {                return false;            }        });    }    @Override    protected void onDestroy() {        super.onDestroy();        //在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理        mMapView.onDestroy();        locationService.unregisterListener(myListener);    }    @Override    protected void onResume() {        super.onResume();        //在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理        mMapView.onResume();        locationService.start();    }    @Override    protected void onPause() {        super.onPause();        //在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理        mMapView.onPause();        locationService.stop();    }    @TargetApi(23)    private void getPersimmions() {        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {            ArrayList<String> permissions = new ArrayList<String>();            /***             * 定位权限为必须权限,用户如果禁止,则每次进入都会申请             */            // 定位精确位置            if(checkSelfPermission(Manifest.permission.access_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);            }            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);            }			/*			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次,用户同意或者禁止,只会弹一次			 */            // 读写权限            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny /n";            }            // 读取电话状态权限            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny /n";            }            if (permissions.size() > 0) {                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);            }        }    }    @TargetApi(23)    private boolean addPermission(ArrayList<String> permissionsList, String permission) {        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请            if (shouldShowRequestPermissionRationale(permission)){                return true;            }else{                permissionsList.add(permission);                return false;            }        }else{            return true;        }    }    @TargetApi(23)    @Override    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {        // TODO Auto-generated method stub        super.onRequestPermissionsResult(requestCode, permissions, grantResults);    }}
MyLocationListener.java
package example.com.baidumaptest;import android.util.Log;import com.baidu.location.BDLocation;import com.baidu.location.BDLocationListener;import com.baidu.location.Poi;import com.baidu.mapapi.map.BitmapDescriptor;import com.baidu.mapapi.map.BitmapDescriptorFactory;import com.baidu.mapapi.map.MapStatusUpdate;import com.baidu.mapapi.map.MapStatusUpdateFactory;import com.baidu.mapapi.map.MarkerOptions;import com.baidu.mapapi.map.MyLocationData;import com.baidu.mapapi.map.Overlay;import com.baidu.mapapi.map.OverlayOptions;import com.baidu.mapapi.model.LatLng;import java.util.List;/** * Created by cherish on 2017/2/5. */public class MyLocationListener implements BDLocationListener {    @Override    public void onReceiveLocation(BDLocation location) {        //Receive Location        StringBuffer sb = new StringBuffer(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() + " " + p.getName() + " " + p.getRank());            }        }        Log.i("BaiduLocationApiDem", sb.toString());        MainActivity.msu = MapStatusUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude()));        MainActivity.baiduMap.setMapStatus(MainActivity.msu);        // 构造定位数据        MyLocationData locData = new MyLocationData.Builder()                .accuracy(location.getRadius())//                .direction(location.getDirection())// 方向                .latitude(location.getLatitude())//                .longitude(location.getLongitude())//                .build();        // 设置定位数据        MainActivity.baiduMap.setMyLocationData(locData);        /*LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(ll);*///功能未明无视,设置新中心点        /*BitmapDescriptor mCurrentMarker= BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher);        OverlayOptions option = new MarkerOptions()                .position(ll)                .icon(mCurrentMarker);       MainActivity.baiduMap.addOverlay(option);//设置覆盖物图标*/    }}
Utils.java
package example.com.baidumaptest;/** * Created by cherish on 2017/2/6. */public class Utils {    public final static String CoorType_GCJ02 = "gcj02";    public final static String CoorType_BD09LL= "bd09ll";    public final static String CoorType_BD09MC= "bd09";    /***     *61 : GPS定位结果,GPS定位成功。     *62 : 无法获取有效定位依据,定位失败,请检查运营商网络或者wifi网络是否正常开启,尝试重新请求定位。     *63 : 网络异常,没有成功向服务器发起请求,请确认当前测试手机网络是否通畅,尝试重新请求定位。     *65 : 定位缓存的结果。     *66 : 离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果。     *67 : 离线定位失败。通过requestOfflineLocaiton调用时对应的返回结果。     *68 : 网络连接失败时,查找本地离线定位时对应的返回结果。     *161: 网络定位结果,网络定位定位成功。     *162: 请求串密文解析失败。     *167: 服务端定位失败,请您检查是否禁用获取位置信息权限,尝试重新请求定位。     *502: key参数错误,请按照说明文档重新申请KEY。     *505: key不存在或者非法,请按照说明文档重新申请KEY。     *601: key服务被开发者自己禁用,请按照说明文档重新申请KEY。     *602: key mcode不匹配,您的ak配置过程中安全码设置有问题,请确保:sha1正确,“;”分号是英文状态;且包名是您当前运行应用的包名,请按照说明文档重新申请KEY。     *501~700:key验证失败,请按照说明文档重新申请KEY。     */    public static float[] EARTH_WEIGHT = {0.1f,0.2f,0.4f,0.6f,0.8f}; // 推算计算权重_地球    //public static float[] MOON_WEIGHT = {0.0167f,0.033f,0.067f,0.1f,0.133f};    //public static float[] MARS_WEIGHT = {0.034f,0.068f,0.152f,0.228f,0.304f};}activity_main.xml
<?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">    <com.baidu.mapapi.map.TextureMapView        android:id="@+id/bmapView"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:clickable="true" /></LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="example.com.baidumaptest">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/APPTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote">        </service>        <meta-data            android:name="com.baidu.lbsapi.API_KEY"            android:value="KZj8EdRhai6a2DrGSgH7BGuOBnBD6fK9" />    </application>    <!-- 这个权限用于进行网络定位-->    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>    <!-- 这个权限用于访问GPS定位-->    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>    <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>    <!-- 获取运营商信息,用于支持提供运营商信息相关的接口-->    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>    <!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>    <!-- 用于读取手机当前的状态-->    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>    <!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据-->    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <!-- 访问网络,网络定位需要上网-->    <uses-permission android:name="android.permission.INTERNET" />    <!-- SD卡读取权限,用户写入离线定位数据-->    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/></manifest>主要so文件需要导入到main》jniLibs
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表