这是写完例子程序之后所写的一些总结,觉得还是用高德好,百度文档,demo例子版本不同,eclipse与AS的例子也不全,所以很累人。
1.添加权限:
在application中添加
android:value="百度API_KEY" />
android:enabled="true"
android:process=":remote" >
这里的"百度API_KEY"是自己去百度申请的,先要有百度开发者账号,然后通过一系列流程申请Key。
没有按照合理的顺序去写在一个Activity中,这样的例子没有实用性,一般全局初始化的东西都是放在Application类中 当然你应该在上面的application中指明name;
public class LocationApplication extends Application {
public LocationService locationService;
public Vibrator mVibrator;
@Override
public void onCreate() {
super.onCreate();
SDKInitializer.initialize(getApplicationContext());
locationService = new LocationService(getApplicationContext());
mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
}
}
做了一系列初始化操作。
public class LocationService {
private LocationClient client = null;
private LocationClientOption mOption,DIYoption;
private Object objLock = new Object();
private Context context;
/***
*
* @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);
}
return isSuccess;
}
public LocationClientOption getOption(){
return DIYoption;
}
/***
*
* @return DefaultLocationClientOption
*/
public LocationClientOption getDefaultLocationClientOption(){
if(mOption == null){
mOption = new LocationClientOption();
/*Battery_Saving
低功耗模式
Device_Sensors
仅设备(Gps)模式
Hight_Accuracy
高精度模式
* 可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
*/
mOption.setLocationMode(LocationMode.Battery_Saving
);
mOption.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系
mOption.setScanSpan(3000);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
mOption.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
mOption.setIsNeedLocationDescribe(true);
mOption.setOpenGps(true);//可选,默认false,设置是否使用gps
mOption.setLocationNotify(true);//可选,默认false,设置是否当GPS有效时按照1S/1次频率输出GPS结果
mOption.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
mOption.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
mOption.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
mOption.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集
mOption.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤GPS仿真结果,默认需要
}
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();
}
}
}
}
1.初始化LocationClient
2.配置定位SDK参数,LocationClientOption
3.实现BDLocationListener接口
4.开始定位 client.start()
写一个基类LocationActivity来判断是否获取了权限
public class LocationActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPersimmions();
}
private final int SDK_PERMISSION_REQUEST = 127;
private String permissionInfo="";
@TargetApi(23)
private void getPersimmions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ArrayList
/***
* 定位权限为必须权限,用户如果禁止,则每次进入都会申请
*/
// 定位精确位置
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
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
if (shouldShowRequestPermissionRationale(permission)){
return true;
}else{
permissionsList.add(permission);
return false;
}
}else{
return true;
}
}
public void updateSomething(Bundle bundle){};
}
MainActivity中布局文件:
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.activity.MainActivity"
android:orientation="vertical">
android:layout_height="wrap_content"
android:orientation="horizontal" >
android:layout_height="wrap_content"
android:text="@string/hello_world" />
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
protected void onStart() {
super.onStart();
locService.registerListener(mMyLocationListener);
LocationClientOption option = locService.getDefaultLocationClientOption();
option.setScanSpan(5000);
locService.setLocationOption(option);
locService.start();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initClick();
}
private void initView(){
btn_stopLoc = (Button) findViewById(R.id.btn_stopLoc);
mMapView = (MapView) findViewById(R.id.bmapView);
mMapView.setLogoPosition(LogoPosition.logoPostionRightBottom);
mMapView.removeViewAt(1);
mBaiduMap = mMapView.getMap();
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(15));//缩放等级
locService = ((LocationApplication) getApplication()).locationService;
}
private void initClick(){
btn_stopLoc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
locService.unregisterListener(mMyLocationListener);
locService.stop();
}
});
//点击标注
mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker mk) {
Bundle bundle = mk.getExtraInfo();
MarkerInfo mkInfo = (MarkerInfo) bundle.getSerializable("info");
if(mkInfo.getImgId()==0){
Toast.makeText(MainActivity.this,
"好多美女啊,她们在 纬度:"+mkInfo.getLatitude()+",经度:"+mkInfo.getLongitude(),
1).show();
}
return false;
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
locService.unregisterListener(mMyLocationListener);
locService.stop();
mMapView.onDestroy();
}
protected void onResume() {
super.onResume();
mMapView.onResume();
}
protected void onPause() {
super.onPause();
// 在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
在地图上更新位置用Handler
private Handler locHander = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
try {
BDLocation location = msg.getData().getParcelable("loc");
// int iscal = msg.getData().getInt("iscalculate");
if (location != null) {
if(mBaiduMap!=null){
mBaiduMap.clear();
}
LatLng point = new LatLng(location.getLatitude(), location.getLongitude());
// 构建Marker图标
BitmapDescriptor bitmap = null;
bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_openmap_focuse_mark); // 推算结果
// 构建MarkerOption,用于在地图上添加Marker
OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
// 在地图上添加Marker,并显示
Marker marker = (Marker)mBaiduMap.addOverlay(option);
marker.setTitle("这是帅比所在地,点我看更多帅比");
//线段
if(mHistoryList!=null&&mHistoryList.size()>1){
option = new PolylineOptions().width(5)
.colorsValues(mColorList)
.points(mHistoryList);
}
mBaiduMap.addOverlay(option);
/*
* 转化传来的参数到自定义的MarkerInfo中
* double latitude,
* double longitude,
* String name,
* int imgId,
* String description
*/
MarkerInfo markInfo = new MarkerInfo(
location.getLatitude(),location.getLongitude(),
"我自己",0,
location.getAddrStr());
Bundle bundle = new Bundle();
bundle.putSerializable("info", markInfo);
marker.setExtraInfo(bundle);
//infowindow中的布局
TextView tv = new TextView(MainActivity.this);
tv.setBackgroundResource(R.drawable.btn_avc_press);
tv.setPadding(20, 10, 20, 20);
tv.setGravity(Gravity.CENTER);
tv.setTextColor(android.graphics.Color.BLUE);
tv.setText(marker.getTitle());
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(tv);
//infowindow位置
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//infowindow点击事件
OnInfoWindowClickListener listener = new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick() {
//隐藏infowindow
mBaiduMap.hideInfoWindow();
}
};
//显示infowindow,-87是偏移量,使infowindow向上偏移,不会挡住marker
InfoWindow infoWindow = new InfoWindow(bitmapDescriptor, latLng, -87, listener);
mBaiduMap.showInfoWindow(infoWindow);
mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));//更新地图状态
}
} catch (Exception e) {
e.printStackTrace();
}
}
};