直接上效果图:
2019-10-17 18:20:16.079 12664-12664/com.example.baidumapdemo I/location: 地址为====四川省宜宾市长宁县Y026 滩子塆 长宁畅通机动车检测有限公司 山水淯江 桂坪村 坪上 长宁县长宁镇海水村村民委员会 三里半烟花爆竹五金销售点 宜宾市 长宁县
2019-10-17 18:20:16.684 12664-12664/com.example.baidumapdemo I/location: address.getLocality()==宜宾市
2019-10-17 18:20:16.684 12664-12664/com.example.baidumapdemo I/location: address.getSubLocality()=2=长宁县
2019-10-17 18:20:16.684 12664-12664/com.example.baidumapdemo I/location: address.getSubLocality()=3=四川省宜宾市长宁县Y026
2019-10-17 18:20:16.698 12664-12664/com.example.baidumapdemo I/location: 经纬度为===Latitude:28.546816758039256
Longitude:104.91863304511612
2019-10-17 18:20:16.699 12664-12664/com.example.baidumapdemo I/location: 地址为====四川省宜宾市长宁县Y026 滩子塆 长宁畅通机动车检测有限公司 山水淯江 桂坪村 坪上 长宁县长宁镇海水村村民委员会 三里半烟花爆竹五金销售点 宜宾市 长宁县
主要是实现的功能有:多点标记 并显示你最新的一个点所在的位置信息,滑动时到某个区域显示当前区域的位置信息,当然还有简单的开启app显示当前位置
首先为了感谢老东家 先上一个百度SDK文档的入口-> 文档入口点击这里
ps:那些简单的SDK接入 jar包的解析我这里就不讲 官方文档中的说明很详细 (不要忘记将你的key配置到manifest中)
ok 废话不多说 咱直接开始咯
权限:
<!-- 访问网络,进行地图相关业务数据请求,包括地图数据,路线规划,POI检索等 -->
<uses-permission android:name="android.permission.INTERNET" /> <!-- 获取网络状态,根据网络状态切换进行数据请求网络转换 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 读取外置存储。如果开发者使用了so动态加载功能并且把so文件放在了外置存储区域,则需要申请该权限,否则不需要 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- 写外置存储。如果开发者使用了离线地图,并且数据写在外置存储区域,则需要申请该权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 这个权限用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 这个权限用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2.主活动中:
详细说明2个方法
1.对于当前点击坐标的位置打印以及详细的位置信息提示框
private void updateWithNewLocation(LatLng latLng) {//移动到具体的位置
String coordinate;
String addressStr = "no address \n";
if (latLng != null) {
beiwei = latLng.latitude - 0.004;
dongjing = latLng.longitude - 0.01;
//double lat = 39.25631486;
//double lng = 115.63478961;
coordinate = "Latitude:" + beiwei + "\nLongitude:" + dongjing;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(beiwei,
dongjing, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append(" ");
}
/*sb.append(address.getCountryName());
Log.i("location", "address.getCountryName()==" + address.getCountryName());//国家名*/
sb.append(address.getLocality()).append(" ");
Log.i("location", "address.getLocality()==" + address.getLocality());//城市名
sb.append(address.getSubLocality());
Log.i("location", "address.getSubLocality()=2=" + address.getSubLocality());//---区名
addressStr = sb.toString();
Log.i("location", "address.getSubLocality()=3=" + address.getAddressLine(0) + "");//---区名
//用来构造InfoWindow的Button
Button button = new Button(getApplicationContext());
button.setBackgroundResource(R.drawable.duihuakuang);
button.setText(address.getAddressLine(0) + "");
//构造InfoWindow
//point 描述的位置点
//-100 InfoWindow相对于point在y轴的偏移量
InfoWindow mInfoWindow = new InfoWindow(button, latLng, -50);
//使InfoWindow生效
mBaiduMap.showInfoWindow(mInfoWindow);
// text_detailedaddress.setText();
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
//如果用户没有允许app访问位置信息 则默认取上海松江经纬度的数据
/*lat = 39.25631486;
lng = 115.63478961;*/
coordinate = "no coordinate!\n";
}
Log.i("location", "经纬度为===" + coordinate);
Log.i("location", "地址为====" + addressStr);
//text_detailedaddress.setText(addressStr + "");
}
2.点击当前坐标 显示标记
private void updateMarkMoveTo(LatLng lat) {//指定位置进行标记
//定义Maker坐标点
LatLng point = new LatLng(lat.latitude, lat.longitude);
//构建Marker图标
BitmapDescriptor bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.biaoji);
//构建MarkerOption,用于在地图上添加Marker
OverlayOptions option = new MarkerOptions()
.position(point)
.icon(bitmap);
//在地图上添加Marker,并显示
mBaiduMap.addOverlay(option);
}
所有的实现代码
public class MainActivity extends AppCompatActivity {
private MapView mMapView;
private BaiduMap mBaiduMap;
private LocationClient mLocationClient;
private double beiwei,dongjing;
private boolean isfirstLocate =true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
//SDKInitializer.setCoordType(CoordType.BD09LL);
setContentView(R.layout.activity_main);
initView();//加载需要的权限
initLocation();//主要实现逻辑
}
private void initLocation() {
mMapView = findViewById(R.id.bmapView);
//设置缩放的级别
// MapStatus.Builder builder = new MapStatus.Builder();
// builder.zoom(18.0f);
// mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
mBaiduMap = mMapView.getMap();
//普通地图 ,mBaiduMap是地图控制器对象
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
mBaiduMap.setMyLocationEnabled(true);//开启地图的定位图层
//定位初始化
mLocationClient = new LocationClient(this);
//通过LocationClientOption设置LocationClient相关参数
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);
//设置locationClientOption
mLocationClient.setLocOption(option);
//注册LocationListener监听器
MyLocationListener myLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(myLocationListener);
//开启地图定位图层
mLocationClient.start();
//自定义
// MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,true,null,0xAAFFFF88,0xAA00FF00);
// mBaiduMap.setMyLocationConfiguration(myLocationConfiguration);
mBaiduMap.setIndoorEnable(true);//打开室内图,默认为关闭状态
//通过设置enable为true或false 选择是否显示缩放按钮
mMapView.showZoomControls(true);
UiSettings mUisettings = mBaiduMap.getUiSettings();
//通过设置enable为true或false 选择是否启用地图平移
mUisettings.setScrollGesturesEnabled(true);
//通过设置enable为true或false 选择是否启用地图缩放手势
mUisettings.setZoomGesturesEnabled(true);
//通过设置enable为true或false 选择是否启用地图俯视功能
mUisettings.setOverlookingGesturesEnabled(true);
//通过设置enable为true或false 选择是否启用地图旋转功能
mUisettings.setRotateGesturesEnabled(true);
initClick();
}
private void initClick() {
mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
/**
* 手势操作地图,设置地图状态等操作导致地图状态开始改变。
*
* @param mapStatus 地图状态改变开始时的地图状态
*/
@Override
public void onMapStatusChangeStart(MapStatus mapStatus) {
}
/**
* 手势操作地图,设置地图状态等操作导致地图状态开始改变。
*
* @param mapStatus 地图状态改变开始时的地图状态
*
* @param i 地图状态改变的原因
*/
//用户手势触发导致的地图状态改变,比如双击、拖拽、滑动底图
//int REASON_GESTURE = 1;
//SDK导致的地图状态改变, 比如点击缩放控件、指南针图标
//int REASON_API_ANIMATION = 2;
//开发者调用,导致的地图状态改变
//int REASON_DEVELOPER_ANIMATION = 3;
@Override
public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
}
/**
* 地图状态变化中
*
* @param mapStatus 当前地图状态
*/
@Override
public void onMapStatusChange(MapStatus mapStatus) {
}
/**
* 地图状态改变结束
*
* @param mapStatus 地图状态改变结束后的地图状态
*/
@Override
public void onMapStatusChangeFinish(MapStatus mapStatus) {
LatLng latLng = mapStatus.target;
updateWithNewLocation(latLng);
}
});
//单击事件
BaiduMap.OnMapClickListener listener = new BaiduMap.OnMapClickListener() {
/**
* 地图单击事件回调函数
*
* @param point 点击的地理坐标
*/
@Override
public void onMapClick(LatLng point) {
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(point);
mBaiduMap.animateMapStatus(update);
//设置缩放值
update = MapStatusUpdateFactory.zoomTo(16f);
mBaiduMap.animateMapStatus(update);
beiwei = point.latitude - 0.004;
dongjing = point.longitude - 0.01;
Log.i("danji",beiwei+"@@"+dongjing);
updateMarkMoveTo(point);//指定位置进行标记
updateWithNewLocation(point);
}
/**
* 地图内 Poi 单击事件回调函数
*
* @param mapPoi 点击的 poi 信息
*/
@Override
public void onMapPoiClick(MapPoi mapPoi) {
Log.i("danji",""+mapPoi.getName());
Toast.makeText(MainActivity.this,mapPoi.getName(),Toast.LENGTH_SHORT).show();
}
};
//设置地图单击事件监听
mBaiduMap.setOnMapClickListener(listener);
}
private void updateMarkMoveTo(LatLng lat) {//指定位置进行标记
//定义Maker坐标点
LatLng point = new LatLng(lat.latitude, lat.longitude);
//构建Marker图标
BitmapDescriptor bitmap = BitmapDescriptorFactory
.fromResource(R.drawable.biaoji);
//构建MarkerOption,用于在地图上添加Marker
OverlayOptions option = new MarkerOptions()
.position(point)
.icon(bitmap);
//在地图上添加Marker,并显示
mBaiduMap.addOverlay(option);
}
private void updateWithNewLocation(LatLng latLng) {//移动到具体的位置
String coordinate;
String addressStr = "no address \n";
if (latLng != null) {
beiwei = latLng.latitude - 0.004;
dongjing = latLng.longitude - 0.01;
//double lat = 39.25631486;
//double lng = 115.63478961;
coordinate = "Latitude:" + beiwei + "\nLongitude:" + dongjing;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(beiwei,
dongjing, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append(" ");
}
/*sb.append(address.getCountryName());
Log.i("location", "address.getCountryName()==" + address.getCountryName());//国家名*/
sb.append(address.getLocality()).append(" ");
Log.i("location", "address.getLocality()==" + address.getLocality());//城市名
sb.append(address.getSubLocality());
Log.i("location", "address.getSubLocality()=2=" + address.getSubLocality());//---区名
addressStr = sb.toString();
Log.i("location", "address.getSubLocality()=3=" + address.getAddressLine(0) + "");//---区名
//用来构造InfoWindow的Button
Button button = new Button(getApplicationContext());
button.setBackgroundResource(R.drawable.duihuakuang);
button.setText(address.getAddressLine(0) + "");
//构造InfoWindow
//point 描述的位置点
//-100 InfoWindow相对于point在y轴的偏移量
InfoWindow mInfoWindow = new InfoWindow(button, latLng, -50);
//使InfoWindow生效
mBaiduMap.showInfoWindow(mInfoWindow);
// text_detailedaddress.setText();
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
//如果用户没有允许app访问位置信息 则默认取上海松江经纬度的数据
/*lat = 39.25631486;
lng = 115.63478961;*/
coordinate = "no coordinate!\n";
}
Log.i("location", "经纬度为===" + coordinate);
Log.i("location", "地址为====" + addressStr);
//text_detailedaddress.setText(addressStr + "");
}
private void initView() {
List<String> permission = new ArrayList<>();
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
permission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
permission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
permission.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
permission.add(Manifest.permission.ACCESS_FINE_LOCATION);
if(!permission.isEmpty()){
String[] permissions = permission.toArray(new String[permission.size()]);
ActivityCompat.requestPermissions(MainActivity.this,permissions,1);//发起权限
}else {
initLocation();
}
}
}
@Override
protected void onResume() {
mMapView.onResume();
super.onResume();
}
@Override
protected void onPause() {
mMapView.onPause();
super.onPause();
}
@Override
protected void onDestroy() {
mLocationClient.stop();
mBaiduMap.setMyLocationEnabled(false);
mMapView.onDestroy();
mMapView = null;
super.onDestroy();
}
//构造地图数据
// 我们通过继承抽象类BDAbstractListener并重写其onReceieveLocation方法来获取定位数据,并将其传给MapView。
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
//mapView 销毁后不在处理新接收的位置
if (location == null || mMapView == null){
return;
}
beiwei = location.getLatitude();
dongjing = location.getLongitude();
navagitto(location);//移动到指定位置
MyLocationData locData = new MyLocationData.Builder()//小圆点哦
.accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(location.getDirection()).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
mBaiduMap.setMyLocationData(locData);
}
}
private void navagitto(BDLocation location) {
if(isfirstLocate){
//更新到指定的经纬度
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(latLng);
mBaiduMap.animateMapStatus(update);
//设置缩放值
update = MapStatusUpdateFactory.zoomTo(16f);
mBaiduMap.animateMapStatus(update);
isfirstLocate = false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {//权限判断的回掉
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){//请求码
case 1:
if(grantResults.length>0){
for(int result :grantResults){
if(result!=PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this,"必须同意所有权限才可以使用",Toast.LENGTH_SHORT).show();
finish();
return;
}
}
initLocation();
}else{
Toast.makeText(MainActivity.this,"发生未知错误,请重试",Toast.LENGTH_SHORT).show();
finish();
}
break;
}
}
}
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" />
</LinearLayout>
ok这样就完成了