1 初始化
在 Application 中或 Activity,Fragment中初始化
SDKInitializer.initialize(this);
2 在xml文件中放置地图控件
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" />
3 定位的两种方式
①直接使用LocationClient
private void initMapLoc() {
map = bmapView.getMap();
map.setTrafficEnabled(true);
// 开启定位图层
map.setMyLocationEnabled(true);
// 定位初始化
BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
.fromResource(R.drawable.own_loc_icon);
map.setMyLocationConfigeration(new MyLocationConfiguration(
LocationMode.FOLLOWING, true, mCurrentMarker, 0xAAFFFF88,
0xAA00FF00));
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);
mLocClient.setLocOption(option);
mLocClient.start();
}
/**
* 定位SDK监听函数
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 销毁后不在处理新接收的位置
if (location == null || map == null) {
return;
}
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(100).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
map.setMyLocationData(locData);
if (isFirstLoc || hasTarget) {
isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatus.Builder builder = new MapStatus.Builder();
builder.target(ll).zoom(12);
map.animateMapStatus(MapStatusUpdateFactory
.newMapStatus(builder.build()));
cenpt = ll;
mLocClient.stop();
}
if (!hasTarget) {
searchCityCloud();
} else {
hasTarget = false;
}
}
public void onReceivePoi(BDLocation poiLocation) {
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 退出时销毁定位
mLocClient.stop();
// 关闭定位图层
map.setMyLocationEnabled(false);
bmapView.onDestroy();
bmapView = null;
}
@Override
public void onPause() {
super.onPause();
bmapView.onPause();
mLocClient.stop();
CloudManager.getInstance().destroy();
}
@Override
public void onResume() {
super.onResume();
bmapView.onResume();
}
② 包装到service
/***
* Stop location service
*/
@Override
protected void onStop() {
// TODO Auto-generated method stub
locationService.unregisterListener(listener); // 注销掉监听
locationService.stop(); // 停止定位服务
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
// -----------location config ------------
locationService = ((TyhcApplication) getApplication()).locationService;
// 获取locationservice实例,建议应用中只初始化1个location实例,然后使用,可以参考其他示例的activity,都是通过此种方式获取locationservice实例的
locationService.registerListener(listener);
// 注册监听
int type = getIntent().getIntExtra("from", 0);
if (type == 0) {
locationService