最近做了个应用,里面用到了百度地图,具体需求是:
1. 输入地址,点击“定位”按钮,跳转到百度地图页面,搜索并显示定位点在该地址;
2. 不输入地址,点击“定位”按钮,跳转到百度地图,显示当前位置;
3. 在百度地图页面,点击某一位置,使定位点移动到此处,点击“确定”,返回经纬度到上一页面;
4. 根据已有的经纬度,点击“定位”,跳转到百度地图,定位到相应位置;
具体代码如下:
1. 第一个页面的xml
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:background="@drawable/bg_enforce_border"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="地址:"
style="@style/enforce_text_label_style"
android:layout_gravity="center_vertical"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/tv_addr"
android:text=""
android:layout_weight="4"
android:layout_width="0dp"
android:gravity="right"
android:background="@color/trans"
style="@style/enforce_text_style_padding"
android:layout_marginRight="@dimen/px30"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:background="@drawable/bg_enforce_border"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="经度:"
style="@style/enforce_text_label_style"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_lng"
android:text=""
android:layout_weight="4"
android:layout_width="0dp"
android:gravity="right"
style="@style/enforce_text_style"
android:layout_marginRight="@dimen/px30"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:background="@drawable/bg_enforce_border"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="纬度:"
style="@style/enforce_text_label_style"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_marginRight="@dimen/px30"
android:layout_weight="4"
android:layout_width="0dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_lat"
android:text=""
android:gravity="right"
android:paddingRight="@dimen/px30"
android:layout_width="match_parent"
android:layout_toLeftOf="@+id/btn_local"
style="@style/enforce_text_style_padding"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/btn_local"
android:text="定位"
android:background="@drawable/bg_button_radius_bluedark"
android:textColor="@color/colorTextWhite"
android:padding="@dimen/px20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
2. 页面代码:
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_local:
requestPermission();
break;
}
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= 23 ) {
// isPermissionRequested = true;
ArrayList<String> permissionsList = new ArrayList<>();
String[] permissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
for (String perm : permissions) {
if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(perm)) {
permissionsList.add(perm);
// 进入到这里代表没有权限.
}
}
if (!permissionsList.isEmpty()) {
Log.e(TAG,"permissionsList.isEmpty()="+permissionsList.isEmpty());
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), 0);
} else {
Intent intent = new Intent(mContext, MapForOfficeActivity.class);
String latStr = tv_lat.getText().toString();
String lntStr = tv_lng.getText().toString();
if (latStr != null && !latStr.equals("") && lntStr != null && !lntStr.equals("")) {
intent.putExtra("latitude",Double.valueOf(latStr));
intent.putExtra("longitude", Double.valueOf(lntStr));
} else {
String addStr = tv_addr.getText().toString();
if (addStr != null && !addStr.equals("")) {
intent.putExtra("address", addStr);
}
}
startActivityForResult(intent,2004);
}
}
}
@Override
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
super.onPermissionsGranted(requestCode, perms);
LogUtil.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
Intent intent = new Intent(mContext, MapForOfficeActivity.class);
String latStr = tv_lat.getText().toString();
String lntStr = tv_lng.getText().toString();
if (latStr != null && !latStr.equals("") && lntStr != null && !lntStr.equals("")) {
intent.putExtra("latitude",Double.valueOf(latStr));
intent.putExtra("longitude", Double.valueOf(lntStr));
} else {
String addStr = tv_addr.getText().toString();
if (addStr != null && !addStr.equals("")) {
intent.putExtra("address", addStr);
}
}
startActivityForResult(intent,2004);
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
super.onPermissionsDenied(requestCode, perms);
LogUtil.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());
// (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
// This will display a dialog directing them to enable the permission in app settings.
// if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
// //new AppSettingsDialog.Builder(this).build().show();
// LogUtil.d(TAG, "onPermissionsDenied: denied any permissions");
// showPermissionDialog();
// } else {
// }
ToastUtils.showMsg("已拒绝相机访问权限,请重新授权");
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2004 && resultCode == RESULT_OK) {
Log.e(TAG,"data="+data.getData()+","+data.getDataString());
double lat = data.getDoubleExtra("latitude",0);
double lnt = data.getDoubleExtra("longitude",0);
String addr = data.getStringExtra("address");
Log.e(TAG,"addr="+addr);
tv_lat.setText(String.valueOf(lat));
tv_lng.setText(String.valueOf(lnt));
}
}
3. 地图页面 MapForOfficeActivity.java
public class MapForOfficeActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "MapForOfficeActivity";
private MapView mMapView;
private BaiduMap mBaiduMap;
public LocationClient mLocClient = null;
private MyLocationListener myListener = new MyLocationListener();
boolean isFirstLoc = true; // 是否首次定位
private double mLatitude;
private double mLongitude;
private String mAddress;
private void initMap() {
mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
MyLocationConfiguration.LocationMode.NORMAL, true, BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding),
0x0f1679b3, 0xAA00FF00));
// 开启定位图层
mBaiduMap.setMyLocationEnabled(true);
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
option.setOpenGps(true); // 打开gps
option.setIsNeedAddress(true);
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(3000);
mLocClient.setLocOption(option);
mLocClient.start();
}
@Override
public void onBeforeSetContentView() {
}
@Override
public int getLayoutResID() {
return R.layout.activity_map_for_office;
}
@Override
public void initContentView(@Nullable Bundle savedInstanceState) {
}
@Override
public void initData(@Nullable Bundle savedInstanceState) {
mLatitude = getIntent().getDoubleExtra("latitude", 0.0f);
mLongitude = getIntent().getDoubleExtra("longitude", 0.0f);
mAddress = getIntent().getStringExtra("address");
Log.e(TAG,"mAddress="+mAddress);
if (mAddress != null && !mAddress.equals("")) {
initSearch();
}
initView();
initMap();
}
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
//此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果
//以下只列举部分获取经纬度相关(常用)的结果信息
//更多结果信息获取说明,请参照类参考中BDLocation类中的说明
String province = location.getProvince(); //获取省份
String city = location.getCity(); //获取城市
String district = location.getDistrict(); //获取区县
String street = location.getStreet(); //获取街道信息
mAddress = province + city + district + street;
//获取纬度信息
// mLatitude = location.getLatitude();
// //获取经度信息
// mLongitude = location.getLongitude();
float radius = location.getRadius(); //获取定位精度,默认值为0.0f
String coorType = location.getCoorType();
//获取经纬度坐标类型,以LocationClientOption中设置过的坐标类型为准
int errorCode = location.getLocType();
//获取定位类型、定位错误返回码,具体信息可参照类参考中BDLocation类中的说明
Log.d("flag", "onReceiveLocation: " + mLatitude + ":" + mLongitude + ":" + radius + ":" + errorCode);
if(mLatitude == 0.0 && mLongitude == 0.0) {
MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(location.getDirection())
// .direction(100)
.latitude(location.getLatitude()).longitude(location.getLongitude())
.build();
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
mBaiduMap.setMyLocationData(locData);
} else {
MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(location.getDirection())
.latitude(mLatitude).longitude(mLongitude)
.build();
mBaiduMap.setMyLocationData(locData);
}
if (isFirstLoc) {
isFirstLoc = false;
// LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
LatLng ll = new LatLng(mLatitude, mLongitude);
MapStatus.Builder builder = new MapStatus.Builder();
builder.target(ll).zoom(18.0f);
mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
}
// 当不需要定位图层时关闭定位图层
// mBaiduMap.setMyLocationEnabled(false);
}
}
private void initView() {
TextView title = findViewById(R.id.title);
title.setText("地图");
LinearLayout back = findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
TextView type_normal = findViewById(R.id.type_normal);
TextView type_satellite = findViewById(R.id.type_satellite);
TextView map_position = findViewById(R.id.map_position);
TextView confirm = findViewById(R.id.confirm);
type_normal.setOnClickListener(this);
type_satellite.setOnClickListener(this);
map_position.setOnClickListener(this);
confirm.setOnClickListener(this);
mMapView = findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();
mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Log.e(TAG, "onMapClick latitude: "+latLng.latitude );//经度
}
@Override
public void onMapPoiClick(MapPoi mapPoi) {
Log.e(TAG, "onMapPoiClick latitude: "+mapPoi.getName()+","+mapPoi.getPosition()+","+mapPoi.getUid() );//经度
LatLng latLng = mapPoi.getPosition();
setMarkPoint(latLng.latitude,latLng.longitude);
mLatitude = latLng.latitude;
mLongitude = latLng.longitude;
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.type_normal:
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
break;
case R.id.type_satellite:
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
break;
case R.id.map_position:
mLocClient.start();
break;
case R.id.confirm:
Intent intent = new Intent();
intent.putExtra("latitude", mLatitude);
intent.putExtra("longitude", mLongitude);
intent.putExtra("address", mAddress);
Log.d("flag", "onClick: "+mLatitude+":"+mLongitude+":"+mAddress);
setResult(RESULT_OK, intent);
finish();
break;
}
}
LatLng point;
private void setMarkPoint(double jingdu,double weidu) {
//定义Maker坐标点
mBaiduMap.clear();
point = new LatLng(jingdu, weidu);
//构建Marker图标
BitmapDescriptor bitmap = BitmapDescriptorFactory
.fromResource(R.mipmap.icon_gcoding);
//构建MarkerOption,用于在地图上添加Marker
OverlayOptions option = new MarkerOptions()
.position(point)
.icon(bitmap);
//在地图上添加Marker,并显示
mBaiduMap.addOverlay(option);
}
GeoCoder mSearch;
private void initSearch() {
mSearch = GeoCoder.newInstance();
mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
@Override
public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
Log.e(TAG, "onGetGeoCodeResult latitude: "+geoCodeResult.getLocation() );//经度
LatLng latLng = geoCodeResult.getLocation();
if (latLng != null) {
mLatitude = latLng.latitude;
mLongitude = latLng.longitude;
}
isFirstLoc = true;
}
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
Log.e(TAG, "onGetReverseGeoCodeResult latitude: "+reverseGeoCodeResult.getLocation() );//经度
}
});
mSearch.geocode(new GeoCodeOption().city(mAddress).address(mAddress));
// Address address = getGeoPointBystr(MapForOfficeActivity.this,mAddress);
// Log.e(TAG, "initSearch latitude: "+address.getLatitude()+","+address.getLongitude() );//经度
// mLatitude = address.getLatitude();
// mLongitude = address.getLongitude();
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mLocClient.stop();
mBaiduMap.setMyLocationEnabled(false);
mMapView.onDestroy();
}
}
4. activity_map_for_office.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorActionBar"
android:clipToPadding="true"
android:fitsSystemWindows="true"
android:orientation="vertical"
tools:context=".modules.office.MapForOfficeActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorTextWhite">
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/type_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="地图"
android:textColor="@color/boxing_black" />
<TextView
android:id="@+id/type_satellite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="卫星"
android:textColor="@color/boxing_black" />
</LinearLayout>
<TextView
android:id="@+id/map_position"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="45dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:text="定位"
android:textColor="@color/boxing_black" />
<TextView
android:background="@color/color_333333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/px10"
android:layout_alignParentBottom="true"
android:text="点击单位所在位置获取定位"
android:textColor="@color/colorTextWhite" />
</RelativeLayout>
</LinearLayout>