1. 添加围栏的方法
private MapView mMapView;
private AMap mAMap;
// 当前的坐标点集合,主要用于进行地图的可视区域的缩放
private LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
// 初始化地理围栏
fenceClient = new GeoFenceClient(getApplicationContext());
if (mAMap == null) {
mAMap = mMapView.getMap();
mAMap.getUiSettings().setRotateGesturesEnabled(false);
mAMap.moveCamera(CameraUpdateFactory.zoomBy(6));
setUpMap();
}
// 设置所有maker显示在当前可视区域地图中
LatLngBounds bounds = boundsBuilder.build();
mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));
polygonPoints.clear();
// 地图初始化
mAMap = mMapView.getMap();
// mMapView.setRotation(90);
UiSettings mUiSettings = mAMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(false);//是否显示地图中放大缩小按钮
mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
mUiSettings.setScaleControlsEnabled(true);//是否显示缩放级别 比例尺
mUiSettings.setCompassEnabled(true);
mUiSettings.setRotateGesturesEnabled(false);
mAMap.setMyLocationEnabled(false);
mAMap.moveCamera(CameraUpdateFactory.zoomBy(4));
1.1 圆形围栏添加代码
private void drawCircle(GeoFence fence) {
LatLng center = new LatLng(fence.getCenter().getLatitude(),
fence.getCenter().getLongitude());
// 绘制一个圆形
mAMap.addCircle(new CircleOptions().center(center)
.radius(fence.getRadius()).strokeColor(Const.STROKE_COLOR)
.fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH));
boundsBuilder.include(center);
}
1.2 方形围栏添加方法
private void drawPolygon(GeoFence fence) {
final List> pointList = fence.getPointList();
if (null == pointList || pointList.isEmpty()) {
return;
}
for (List subList : pointList) {
List lst = new ArrayList();
PolygonOptions polygonOption = new PolygonOptions();
for (DPoint point : subList) {
lst.add(new LatLng(point.getLatitude(), point.getLongitude()));
boundsBuilder.include(
new LatLng(point.getLatitude(), point.getLongitude()));
}
polygonOption.addAll(lst);
polygonOption.strokeColor(Const.STROKE_COLOR)
.fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH);
Polygon polygon = mAMap.addPolygon(polygonOption);
// 判断是否在围栏内的函数
// polygon.contains()
// polygon.remove(); // 删除多边形
// polygon.contains()// 判断是否在围栏内的函数
}
}
1.3 添加地图直线
private void drawPolyLine() {
if (polygon != null) {
polygon.remove();
polygon = null;
}
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.addAll(polygonPoints)
.width(5).color(0xFFFEB600);
polyline = mAMap.addPolyline(polylineOptions);
}
2.1 多边形围栏 项目源码
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.fence.GeoFenceListener;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ironant.common.utils.LogUtil;
import com.ironant.common.utils.ToastUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* 多边形地理围栏
*
*
* 判断是否在围栏内的函数
* polygon.contains()
* polygon.remove(); // 删除多边形
*
* @author hongming.wang
* @since 3.2.0
*/
public class MapPolygonAcy extends CheckPermissionsActivity
implements
OnClickListener,
GeoFenceListener,
OnMapClickListener,
LocationSource,
AMapLocationListener,
OnCheckedChangeListener, AMap.OnMapScreenShotListener {
private EditText etCustomId;
private CheckBox cbAlertIn;
private CheckBox cbAlertOut;
private CheckBox cbAldertStated;
private Button btAddFence;
private LatLng center = null;
/**
* 用于显示当前的位置
*
* 示例中是为了显示当前的位置,在实际使用中,单独的地理围栏可以不使用定位接口
*
*/
private AMapLocationClient mlocationClient;
private OnLocationChangedListener mListener;
private AMapLocationClientOption mLocationOption;
private MapView mMapView;
private AMap mAMap;
// 多边形围栏的边界点
private List polygonPoints = new ArrayList();
private List markerList = new ArrayList();
// 当前的坐标点集合,主要用于进行地图的可视区域的缩放
private LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
private BitmapDescriptor bitmap = null;
private MarkerOptions markerOption = null;
// 地理围栏客户端
private GeoFenceClient fenceClient = null;
// 触发地理围栏的行为,默认为进入提醒
private int activatesAction = GeoFenceClient.GEOFENCE_IN;
// 地理围栏的广播action
private static final String GEOFENCE_BROADCAST_ACTION = "com.example.geofence.polygon";
private int markerId = 0;
// 记录已经添加成功的围栏
private HashMap fenceMap = new HashMap();
private Polygon polygon;
private View iv_mapchexiao;
private View iv_mapback;
private View iv_map_sure;
private Polyline polyline;
private float zoom;
@SuppressLint("SourceLockedOrientationActivity")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geofence_new);
// if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// }
// 初始化地理围栏
fenceClient = new GeoFenceClient(getApplicationContext());
btAddFence = (Button) findViewById(R.id.bt_addFence);
etCustomId = (EditText) findViewById(R.id.et_customId);
iv_mapchexiao = findViewById(R.id.iv_mapchexiao);
iv_mapback = findViewById(R.id.iv_mapback);
iv_map_sure = findViewById(R.id.iv_map_sure);
cbAlertIn = (CheckBox) findViewById(R.id.cb_alertIn);
cbAlertOut = (CheckBox) findViewById(R.id.cb_alertOut);
cbAldertStated = (CheckBox) findViewById(R.id.cb_alertStated);
mMapView = (MapView) findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
bitmap = BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW);
markerOption = new MarkerOptions().icon(bitmap).draggable(true);
init();
btAddFence.setEnabled(true);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String center1 = extras.getString("center");
String latlonStr = extras.getString("latlonStr");
// 原来选择过
polygonPoints = new Gson().fromJson(latlonStr, new TypeToken>() {
}.getType());
center = new Gson().fromJson(center1, LatLng.class);
LogUtil.e(center1);
LogUtil.e(latlonStr);
markerId = 0;
drawMap();
}
}
void init() {
if (mAMap == null) {
mAMap = mMapView.getMap();
// mMapView.setRotation(90);
UiSettings mUiSettings = mAMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(false);//是否显示地图中放大缩小按钮
mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
mUiSettings.setScaleControlsEnabled(true);//是否显示缩放级别 比例尺
mUiSettings.setCompassEnabled(true);
mUiSettings.setRotateGesturesEnabled(false);
mAMap.setMyLocationEnabled(false);
mAMap.moveCamera(CameraUpdateFactory.zoomBy(4));
setUpMap();
}
resetView_polygon();
iv_map_sure.setOnClickListener(this);
btAddFence.setOnClickListener(this);
iv_mapback.setOnClickListener(this);
iv_mapchexiao.setOnClickListener(this);
cbAlertIn.setOnCheckedChangeListener(this);
cbAlertOut.setOnCheckedChangeListener(this);
cbAldertStated.setOnCheckedChangeListener(this);
IntentFilter filter = new IntentFilter();
filter.addAction(GEOFENCE_BROADCAST_ACTION);
registerReceiver(mGeoFenceReceiver, filter);
/**
* 创建pendingIntent
*/
fenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
fenceClient.setGeoFenceListener(this);
/**
* 设置地理围栏的触发行为,默认为进入
*/
fenceClient.setActivateAction(GeoFenceClient.GEOFENCE_IN);
mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
// 移动完成后 进行定位
if (null != cameraPosition) {
zoom = cameraPosition.zoom;
LogUtil.e("zoom = " + zoom);
center = new LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude);
}
}
@Override
public void onCameraChange(CameraPosition cameraPosition) {
}
});
}
/**
* 设置一些amap的属性
*/
private void setUpMap() {
mAMap.setOnMapClickListener(this);
mAMap.setLocationSource(this);// 设置定位监听
mAMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
MyLocationStyle myLocationStyle = new MyLocationStyle();
// 自定义定位蓝点图标
myLocationStyle.myLocationIcon(
BitmapDescriptorFactory.fromResource(R.drawable.gps_point));
// 自定义精度范围的圆形边框颜色
myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
// 自定义精度范围的圆形边框宽度
myLocationStyle.strokeWidth(0);
// 设置圆形的填充颜色
myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
// 将自定义的 myLocationStyle 对象添加到地图上
mAMap.setMyLocationStyle(myLocationStyle);
mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
// 设置定位的类型为定位模式 ,可以由定位、跟随或地图根据面向方向旋转几种
mAMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
}
/**
* 方法必须重写
*/
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
/**
* 方法必须重写
*/
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
deactivate();
}
/**
* 方法必须重写
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_map_sure:
// 确定按钮
if (polygonPoints.size() < 3) {
ToastUtils.showShort("最少需要三个点!");
return;
}
showYDialogLand("保存信息...");
mAMap.getMapScreenShot(MapPolygonAcy.this);
LogUtil.e(" --- " + new Gson().toJson(polygonPoints));
break;
case R.id.iv_mapback:
finish();
break;
case R.id.iv_mapchexiao:
removeMarker();
break;
case R.id.bt_addFence:
addFence();
break;
default:
break;
}
}
// 确定选择地址
private void selectOk(String path) {
Intent i = new Intent();
i.putExtra("latlonStr", new Gson().toJson(polygonPoints));
i.putExtra("center", new Gson().toJson(center));
i.putExtra("path", path);
setResult(555, i);
finish();
}
// 原来选择过区域 直接绘制出来
private void drawMap() {
for (int i = 0; i < polygonPoints.size(); i++) {
LatLng latLng = polygonPoints.get(i);
addPolygonMarker(latLng);
}
drawPolygonOnly();
}
private synchronized void removeMarker() {
if (markerList.size() <= 0) {
ToastUtils.showShort("没有可以删除的标记点!!");
return;
}
int index = markerList.size() - 1;
Marker marker = markerList.get(index);
marker.remove();
markerList.remove(marker);
polygonPoints.remove(index);
markerId--;
if (markerList.size() == 2) {
drawPolyLine();
changeMarkerColor(false);
} else if (markerList.size() > 2) {
drawPolygonOnly();
} else if (markerList.size() == 1) {
if (polyline != null) {
polyline.remove();
polyline = null;
}
}
}
private void drawFence(GeoFence fence) {
switch (fence.getType()) {
case GeoFence.TYPE_POLYGON:
case GeoFence.TYPE_DISTRICT:
drawPolygon(fence);
break;
default:
break;
}
// 设置所有maker显示在当前可视区域地图中
LatLngBounds bounds = boundsBuilder.build();
mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));
// polygonPoints.clear();
// removeMarkers();
}
/**
* 绘制多边形
*
* @param fence
*/
private void drawPolygon(GeoFence fence) {
final List> pointList = fence.getPointList();
if (null == pointList || pointList.isEmpty()) {
return;
}
for (List subList : pointList) {
List lst = new ArrayList();
PolygonOptions polygonOption = new PolygonOptions();
for (DPoint point : subList) {
lst.add(new LatLng(point.getLatitude(), point.getLongitude()));
boundsBuilder.include(
new LatLng(point.getLatitude(), point.getLongitude()));
}
polygonOption.addAll(lst);
polygonOption.strokeColor(Const.STROKE_COLOR)
.fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH);
polygon = mAMap.addPolygon(polygonOption);
// 判断是否在围栏内的函数
// polygon.remove(); // 删除多边形
// polygon.contains()
}
}
private void drawPolyLine() {
if (polygon != null) {
polygon.remove();
polygon = null;
}
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.addAll(polygonPoints)
.width(5).color(0xFFFEB600);
polyline = mAMap.addPolyline(polylineOptions);
}
// 画区域
private void drawPolygonOnly() {
// 当第三个标记的时候,去除直线
if (polyline != null) {
changeMarkerColor(true);
polyline.remove();
polyline = null;
}
if (polygon != null) {
polygon.remove();
polygon = null;
}
PolygonOptions polygonOption = new PolygonOptions();
for (LatLng point : polygonPoints) {
boundsBuilder.include(
new LatLng(point.latitude, point.longitude));
}
polygonOption.addAll(polygonPoints);
polygonOption.strokeColor(0xFFFEB600)
.fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH);
polygon = mAMap.addPolygon(polygonOption);
// polygon.remove(); // 删除多边形
// polygon.contains()// 判断是否在围栏内的函数
}
Object lock = new Object();
void drawFence2Map() {
new Thread() {
@Override
public void run() {
try {
synchronized (lock) {
if (null == fenceList || fenceList.isEmpty()) {
return;
}
for (GeoFence fence : fenceList) {
if (fenceMap.containsKey(fence.getFenceId())) {
continue;
}
drawFence(fence);
fenceMap.put(fence.getFenceId(), fence);
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}.start();
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
StringBuffer sb = new StringBuffer();
sb.append("添加围栏成功");
String customId = (String) msg.obj;
if (!TextUtils.isEmpty(customId)) {
sb.append("customId: ").append(customId);
}
Toast.makeText(getApplicationContext(), sb.toString(),
Toast.LENGTH_SHORT).show();
LogUtil.e("添加围栏成功---");
drawFence2Map();
break;
case 1:
int errorCode = msg.arg1;
Toast.makeText(getApplicationContext(),
"添加围栏失败 " + errorCode, Toast.LENGTH_SHORT).show();
break;
case 2:
String statusStr = (String) msg.obj;
LogUtil.e(statusStr);
break;
default:
break;
}
}
};
List fenceList = new ArrayList();
@Override
public void onGeoFenceCreateFinished(final List geoFenceList,
int errorCode, String customId) {
Message msg = Message.obtain();
if (errorCode == GeoFence.ADDGEOFENCE_SUCCESS) {
fenceList.addAll(geoFenceList);
msg.obj = customId;
msg.what = 0;
} else {
msg.arg1 = errorCode;
msg.what = 1;
}
handler.sendMessage(msg);
}
/**
* 接收触发围栏后的广播,当添加围栏成功之后,会立即对所有围栏状态进行一次侦测,如果当前状态与用户设置的触发行为相符将会立即触发一次围栏广播;
* 只有当触发围栏之后才会收到广播,对于同一触发行为只会发送一次广播不会重复发送,除非位置和围栏的关系再次发生了改变。
*/
private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 接收广播
if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
Bundle bundle = intent.getExtras();
String customId = bundle
.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
//status标识的是当前的围栏状态,不是围栏行为
int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
StringBuffer sb = new StringBuffer();
switch (status) {
case GeoFence.STATUS_LOCFAIL:
sb.append("定位失败");
break;
case GeoFence.STATUS_IN:
sb.append("进入围栏 ");
break;
case GeoFence.STATUS_OUT:
sb.append("离开围栏 ");
break;
case GeoFence.STATUS_STAYED:
sb.append("停留在围栏内 ");
break;
default:
break;
}
if (status != GeoFence.STATUS_LOCFAIL) {
if (!TextUtils.isEmpty(customId)) {
sb.append(" customId: " + customId);
}
sb.append(" fenceId: " + fenceId);
}
String str = sb.toString();
Message msg = Message.obtain();
msg.obj = str;
msg.what = 2;
handler.sendMessage(msg);
}
}
};
/**
* 添加标记
*
* @param latLng
*/
@Override
public void onMapClick(LatLng latLng) {
if (null == polygonPoints) {
polygonPoints = new ArrayList();
}
polygonPoints.add(latLng);
addPolygonMarker(latLng);
if (polygonPoints.size() > 2) {
drawPolygonOnly();
} else if (polygonPoints.size() == 2) {
// 绘制直线
drawPolyLine();
}
}
/**
* 定位成功后回调函数
*/
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (mListener != null && amapLocation != null) {
if (amapLocation != null && amapLocation.getErrorCode() == 0) {
mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
center = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
} else {
String errText = "定位失败," + amapLocation.getErrorCode() + ": "
+ amapLocation.getErrorInfo();
Log.e("AmapErr", errText);
}
}
}
/**
* 激活定位
*/
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
if (mlocationClient == null) {
mlocationClient = new AMapLocationClient(this);
mLocationOption = new AMapLocationClientOption();
// 设置定位监听
mlocationClient.setLocationListener(this);
// 设置为高精度定位模式
mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
// 只是为了获取当前位置,所以设置为单次定位
mLocationOption.setOnceLocation(true);
// 设置定位参数
mlocationClient.setLocationOption(mLocationOption);
mlocationClient.startLocation();
}
}
/**
* 停止定位
*/
@Override
public void deactivate() {
mListener = null;
if (mlocationClient != null) {
mlocationClient.stopLocation();
mlocationClient.onDestroy();
}
mlocationClient = null;
}
// 添加多边形的边界点marker
private void addPolygonMarker(LatLng latlng) {
// markerOption.position(latlng);
// Marker marker = mAMap.addMarker(markerOption);
// markerList.add(marker);
markerId++;
//小猫 自定义 Marker
View viewCat = LayoutInflater.from(this).inflate(R.layout.item_marker_view, null);
TextView tv_marker = (TextView) viewCat.findViewById(R.id.tv_marker);
ImageView iv_mark_bg = viewCat.findViewById(R.id.iv_mark_bg);
tv_marker.setText(markerId + "");
int size = markerList.size();
if (size == 0) {
iv_mark_bg.setBackgroundResource(R.mipmap.circle_gray);
} else if (size == 1) {
iv_mark_bg.setBackgroundResource(R.mipmap.circle_gray);
} else {
iv_mark_bg.setBackgroundResource(R.mipmap.circle_yellow);
}
MarkerOptions markerOption = new MarkerOptions().position(latlng)
.draggable(false)
.icon(BitmapDescriptorFactory.fromView(viewCat));
//将数据添加到地图上
Marker marker = mAMap.addMarker(markerOption);
//设置类型为2 为了区分 点击 哪一个类型的Marker
marker.setObject(markerId);
markerList.add(marker);
}
/**
* 当点击第三个标记的时候,修改第一个和第二个 为黄色
* 重置新的布局 ,需要重新设置标记数
*/
private void changeMarkerColor(boolean isYellow) {
int circle_yellow;
if (isYellow) {
circle_yellow = R.mipmap.circle_yellow;
} else {
circle_yellow = R.mipmap.circle_gray;
}
// LogUtil.e("changeMarkerYellow");
View viewCat = LayoutInflater.from(this).inflate(R.layout.item_marker_view, null);
ImageView iv_mark_bg = viewCat.findViewById(R.id.iv_mark_bg);
iv_mark_bg.setBackgroundResource(circle_yellow);
markerList.get(0).setMarkerOptions(new MarkerOptions().position(polygonPoints.get(0))
.draggable(false)
.icon(BitmapDescriptorFactory.fromView(viewCat)));
View viewCat1 = LayoutInflater.from(this).inflate(R.layout.item_marker_view, null);
ImageView iv_mark_bg1 = viewCat1.findViewById(R.id.iv_mark_bg);
iv_mark_bg1.setBackgroundResource(circle_yellow);
TextView tv_marker = viewCat1.findViewById(R.id.tv_marker);
tv_marker.setText("2");
markerList.get(1).setMarkerOptions(new MarkerOptions().position(polygonPoints.get(1))
.draggable(false)
.icon(BitmapDescriptorFactory.fromView(viewCat1)));
}
private void removeMarkers() {
if (null != markerList && markerList.size() > 0) {
for (Marker marker : markerList) {
marker.remove();
}
markerList.clear();
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.cb_alertIn:
if (isChecked) {
activatesAction |= GeoFenceClient.GEOFENCE_IN;
} else {
activatesAction = activatesAction
& (GeoFenceClient.GEOFENCE_OUT
| GeoFenceClient.GEOFENCE_STAYED);
}
break;
case R.id.cb_alertOut:
if (isChecked) {
activatesAction |= GeoFenceClient.GEOFENCE_OUT;
} else {
activatesAction = activatesAction
& (GeoFenceClient.GEOFENCE_IN
| GeoFenceClient.GEOFENCE_STAYED);
}
break;
case R.id.cb_alertStated:
if (isChecked) {
activatesAction |= GeoFenceClient.GEOFENCE_STAYED;
} else {
activatesAction = activatesAction
& (GeoFenceClient.GEOFENCE_IN
| GeoFenceClient.GEOFENCE_OUT);
}
break;
default:
break;
}
if (null != fenceClient) {
fenceClient.setActivateAction(activatesAction);
}
}
private void resetView_polygon() {
polygonPoints = new ArrayList();
btAddFence.setEnabled(false);
}
/**
* 添加围栏
*
* @author hongming.wang
* @since 3.2.0
*/
private void addFence() {
addPolygonFence();
}
/**
* 添加多边形围栏
*
* @author hongming.wang
* @since 3.2.0
*/
private void addPolygonFence() {
String customId = etCustomId.getText().toString();
if (null == polygonPoints || polygonPoints.size() < 3) {
Toast.makeText(getApplicationContext(), "参数不全", Toast.LENGTH_SHORT)
.show();
btAddFence.setEnabled(true);
return;
}
List pointList = new ArrayList();
for (LatLng latLng : polygonPoints) {
LogUtil.e(latLng.latitude + ", lon = " + latLng.longitude);
pointList.add(new DPoint(latLng.latitude, latLng.longitude));
}
fenceClient.addGeoFence(pointList, customId);
}
/**
* 截屏时回调的方法。
*
* @param bitmap 调用截屏接口返回的截屏对象。
*/
@Override
public void onMapScreenShot(Bitmap bitmap) {
}
/**
* 带有地图渲染状态的截屏回调方法。
* 根据返回的状态码,可以判断当前视图渲染是否完成。
*
* @param bitmap 调用截屏接口返回的截屏对象。
* @param arg1 地图渲染状态, 1:地图渲染完成,0:未绘制完成
*/
@Override
public void onMapScreenShot(Bitmap bitmap, int arg1) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
if (null == bitmap) {
return;
}
File fold = new File(Environment.getExternalStorageDirectory() + "/ant/");
if (!fold.exists()) {
fold.mkdirs();
}
try {
String path = Environment.getExternalStorageDirectory() + "/ant/test_" +
sdf.format(new Date()) + ".png";
FileOutputStream fos = new FileOutputStream(path);
boolean b = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
try {
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer buffer = new StringBuffer();
if (b) {
dismissYDialog();
selectOk(path);
buffer.append("截屏成功 ");
} else {
buffer.append("截屏失败 ");
}
if (arg1 != 0) {
buffer.append("地图渲染完成,截屏无网格");
} else {
buffer.append("地图未渲染完成,截屏有网格");
}
// ToastUtil.show(ScreenShotActivity.this, buffer.toString());
LogUtil.e(buffer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
LogUtil.e("e --" + e.getMessage());
}
}
/**
* 方法必须重写
*/
@Override
protected void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
try {
unregisterReceiver(mGeoFenceReceiver);
} catch (Throwable e) {
}
if (null != fenceClient) {
fenceClient.removeGeoFence();
}
if (null != mlocationClient) {
mlocationClient.onDestroy();
}
}
}
2.2 圆形围栏项目源码
/**
* des : 圆形圈点Acy
*/
public class MapActivity extends BaseAppCompatActivity implements
AMap.OnMapScreenShotListener {
private MapView mMapView;
private ImageView mIvBack;
private ImageView mIvSearch;
private ImageView mIvLocation;
private ImageView mIvCenterLocation;
// private Button mBtSend;
private RecyclerView mRecyclerView;
private AddressAdapter mAddressAdapter;
private List mList;
private PoiItem userSelectPoiItem;
private AMap mAMap;
private Marker mMarker, mLocationGpsMarker, mSelectByListMarker;
private UiSettings mUiSettings;
private PoiSearch mPoiSearch;
private PoiSearch.Query mQuery;
private boolean isSearchData = false;//是否搜索地址数据
private int searchAllPageNum;//Poi搜索最大页数,可应用于上拉加载更多
private int searchNowPageNum;//当前poi搜索页数
private AMapLocationClient locationClient = null;
private AMapLocationClientOption locationOption = new AMapLocationClientOption();
private AMapLocation location;
private AMapLocationListener mAMapLocationListener;
private onPoiSearchLintener mOnPoiSearchListener;
private GeocodeSearch.OnGeocodeSearchListener mOnGeocodeSearchListener;
private Gson gson;
private ObjectAnimator mTransAnimator;//地图中心标志动态
private static final int SEARCHREQUESTCODE = 1001;
// 要申请的权限
private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS};
private TextView tvTitle;
private TextView tv_title_right;
private ImageView iv_jia;
private ImageView iv_jian;
private View ll_search;
// 定位区域的半径
private TextView tv_radius;
// 定位的坐标中心点
private LatLng center = null;
private float zoom = 16;//地图缩放级别
private int radiusId = 4; // 最大23
private int radiusArry[] = {5, 10, 25, 50, 100, 200,
300, 400, 500, 600, 700,
800, 900, 1000, 1100, 1200,
1300, 1400, 1500, 1600, 1700,
1800, 1900, 2000};
private ImageView iv_sure;
private ImageView iv_cancle;
private int radiusJL = 100;
private String cityStr = "";
private String addStr = "";
private String latlonStr;
private boolean needMove = false;
private PoiItem rv_index = null;
private AMapLocation searchlocation;
// 5 10 25 50 100 200 -2000
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int radius = extras.getInt("radius");
latlonStr = extras.getString("latlonStr");
String centerStr = extras.getString("center");
if (!latlonStr.equals("")) {
//不为空,代表原来选择过地址
if (TextUtils.isEmpty(centerStr)) {
rv_index = extras.getParcelable("rv_index");
needMove = true;
radiusJL = radius;
center = new Gson().fromJson(latlonStr, LatLng.class);
LogUtil.e("坐标点 是 半径方式");
} else {
ArrayList latLngs = new Gson().fromJson(latlonStr, new TypeToken>() {
}.getType());
// 手动圈点
LogUtil.e("坐标点 是 手动圈点 = " + latLngs.size());
Intent i = new Intent(ctx, MapPolygonAcy.class);
i.putExtra("center", centerStr);
i.putExtra("latlonStr", latlonStr);
startActivityForResult(i, 666);
}
}
}
initView();
initDatas(savedInstanceState);
initListener();
initPermission();
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 区域poi搜索
if (null != data && SEARCHREQUESTCODE == requestCode) {
try {
userSelectPoiItem = (PoiItem) data.getParcelableExtra(DatasKey.SEARCH_INFO);
if (null != userSelectPoiItem) {
isSearchData = false;
cityStr = location.getCity();
doSearchQuery(true, "", location.getCity(), userSelectPoiItem.getLatLonPoint());
moveMapCamera(userSelectPoiItem.getLatLonPoint().getLatitude(), userSelectPoiItem.getLatLonPoint().getLongitude());
drawCirCle(userSelectPoiItem.getLatLonPoint().getLatitude(), userSelectPoiItem.getLatLonPoint().getLongitude());
// refleshMark(userSelectPoiItem.getLatLonPoint().getLatitude(), userSelectPoiItem.getLatLonPoint().getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (null != data && resultCode == 555) {
// 手动圈点
String latlonStr = data.getExtras().getString("latlonStr");
String path = data.getExtras().getString("path");
String center = data.getExtras().getString("center");
LogUtil.e("圆形区域选择 == " + latlonStr);
Intent i = new Intent();
if (location != null) {
cityStr = location.getCity();
}
i.putExtra("center", center);
i.putExtra("cityStr", cityStr);
i.putExtra(addStr, addStr);
i.putExtra("latlonStr", latlonStr);
i.putExtra("raduis", -1);
i.putExtra("path", path);
setResult(777, i);
finish();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
stopLocation();
mMapView.onDestroy();
if (null != mPoiSearch) {
mPoiSearch = null;
}
if (null != gson) {
gson = null;
}
if (null != locationClient) {
locationClient.onDestroy();
}
}
private void initView() {
mMapView = (MapView) findViewById(R.id.map);
mIvBack = (ImageView) findViewById(R.id.iv_back);
// 加减半径
iv_jian = (ImageView) findViewById(R.id.iv_jian);
iv_jia = (ImageView) findViewById(R.id.iv_jia);
iv_sure = (ImageView) findViewById(R.id.iv_sure);
iv_cancle = (ImageView) findViewById(R.id.iv_cancle);
tvTitle = findViewById(R.id.tvTitle);
tv_title_right = findViewById(R.id.tv_title_right);
tv_radius = findViewById(R.id.tv_radius);
mIvSearch = (ImageView) findViewById(R.id.iv_search);
mIvLocation = (ImageView) findViewById(R.id.iv_location);
mIvCenterLocation = (ImageView) findViewById(R.id.iv_center_location);
// mBtSend = (Button) findViewById(R.id.bt_send);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
ll_search = findViewById(R.id.ll_search);
tv_title_right.setText("切换手动圈点");
tv_title_right.setVisibility(View.VISIBLE);
tv_title_right.setOnClickListener(mOnClickListener);
tvTitle.setText("区域选取");
}
private void initListener() {
//监测地图画面的移动
mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
// 移动完成后 进行定位
if (null != location && null != cameraPosition && isSearchData) {
mIvLocation.setImageResource(R.mipmap.location_gps_green);
zoom = cameraPosition.zoom;
if (null != mSelectByListMarker) {
mSelectByListMarker.setVisible(false);
}
getAddressInfoByLatLong(cameraPosition.target.latitude, cameraPosition.target.longitude);
startTransAnimator();
// doSearchQuery(true, "", location.getCity(), new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude));
//
drawCirCle(cameraPosition.target.latitude, cameraPosition.target.longitude);
}
if (!isSearchData) {
isSearchData = true;
}
}
@Override
public void onCameraChange(CameraPosition cameraPosition) {
}
});
//设置触摸地图监听器
mAMap.setOnMapClickListener(new AMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
isSearchData = true;
}
});
//Poi搜索监听器
mOnPoiSearchListener = new onPoiSearchLintener();
//逆地址搜索监听器 地址完成
mOnGeocodeSearchListener = new GeocodeSearch.OnGeocodeSearchListener() {
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
if (i == 1000) {
if (regeocodeResult != null) {
userSelectPoiItem = DataConversionUtils.changeToPoiItem(regeocodeResult);
if (null != mList) {
mList.clear();
}
mList.addAll(regeocodeResult.getRegeocodeAddress().getPois());
if (null != userSelectPoiItem) {
mList.add(0, userSelectPoiItem);
}
addStr = userSelectPoiItem.getProvinceName() + userSelectPoiItem.getCityName() + userSelectPoiItem.getAdName() + userSelectPoiItem.getSnippet();
mAddressAdapter.setList(mList);
if (rv_index != null) {
mList.add(0, rv_index);
mAddressAdapter.setSelectPosition(0);
mRecyclerView.scrollToPosition(0);
rv_index = null;
} else {
mRecyclerView.smoothScrollToPosition(0);
}
} else {
LogUtil.e("regeocodeResult != null");
}
}
}
@Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
}
};
//gps定位监听器
mAMapLocationListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation loc) {
try {
if (null != loc) {
stopLocation();
if (loc.getErrorCode() == 0) {//可在其中解析amapLocation获取相应内容。
location = loc;
SPUtils.putString(MapActivity.this, DatasKey.LOCATION_INFO, gson.toJson(location));
doWhenLocationSucess();
} else {
//定位失败时,可通过ErrCode(错误码)信息来确定失败的原因,errInfo是错误信息,详见错误码表。
showToastWithErrorInfo(loc.getErrorCode());
Log.e("AmapError", "location Error, ErrCode:"
+ loc.getErrorCode() + ", errInfo:"
+ loc.getErrorInfo());
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
//recycleview列表点击监听器
mAddressAdapter.setOnItemClickLisenter(new OnItemClickLisenter() {
@Override
public void onItemClick(int position) {
try {
isSearchData = false;
mIvLocation.setImageResource(R.mipmap.location_gps_green);
PoiItem poiItem = mList.get(position);
moveMapCamera(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
center = new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
drawCirCleRefresh();
addStr = poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet();
// refleshSelectByListMark(mList.get(position).getLatLonPoint().getLatitude(), mList.get(position).getLatLonPoint().getLongitude());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
//控件点击监听器
mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_back:
finish();
break;
case R.id.iv_search:
case R.id.ll_search:
// Toast.makeText(MainActivity.this, "搜索", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(MapActivity.this, SearchActivity.class), SEARCHREQUESTCODE);
break;
case R.id.iv_location:
// 定位
// Toast.makeText(MainActivity.this, "定位", Toast.LENGTH_SHORT).show();
mIvLocation.setImageResource(R.mipmap.location_gps_green);
if (null != mSelectByListMarker) {
mSelectByListMarker.setVisible(false);
}
if (null == location) {
startLocation();
} else {
doWhenLocationSucess();
}
break;
case R.id.iv_jia:
// 地图半径+
if (radiusJL >= 3000) {
ToastUtils.showShort("最大半径是3000!");
return;
}
radiusId++;
radiusJL += 20;
tv_radius.setText(radiusJL + "米");
drawCirCleRefresh();
if ((float) radiusJL / (float) getBILICHILong((int) zoom) > 2.0f) {
// 增加比例尺
zoom -= 1;
mAMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
}
break;
case R.id.iv_jian:
// 地图半径-
if (radiusJL <= 40) {
ToastUtils.showShort("最小半径是40!");
return;
}
radiusId--;
radiusJL -= 20;
tv_radius.setText(radiusJL + "米");
drawCirCleRefresh();
// 比例尺是半径二倍 ,比例搜小 地图看的越详细一些
if ((float) getBILICHILong((int) zoom) / (float) radiusJL > 2.0f) {
// 增加比例尺
zoom += 1;
mAMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
}
break;
case R.id.iv_cancle:
// 重置
radiusId = 4;
tv_radius.setText(radiusArry[radiusId] + "米");
drawCirCleRefresh();
zoom = 16;
mIvLocation.performClick();
break;
case R.id.iv_sure:
// 确定
showYDialog("保存地图信息...");
mAMap.getMapScreenShot(MapActivity.this);
LogUtil.e(" iv_sure ");
break;
case R.id.tv_title_right:
// 手动圈点
startActivityForResult(new Intent(ctx, MapPolygonAcy.class), 666);
break;
/*case R.id.bt_send:
if (null != mList && 0 < mList.size() && null != mAddressAdapter) {
int position = mAddressAdapter.getSelectPositon();
if (position < 0) {
position = 0;
} else if (position > mList.size()) {
position = mList.size();
}
PoiItem poiItem = mList.get(position);
Toast.makeText(MapActivity.this, "发送:" + poiItem.getTitle() + " " + poiItem.getSnippet() + " " + "纬度:" + poiItem.getLatLonPoint().getLatitude() + " " + "经度:" + poiItem.getLatLonPoint().getLongitude(), Toast.LENGTH_SHORT).show();
}
break;*/
}
}
};
mIvBack.setOnClickListener(mOnClickListener);
iv_sure.setOnClickListener(mOnClickListener);
iv_cancle.setOnClickListener(mOnClickListener);
// mIvSearch.setOnClickListener(mOnClickListener);
ll_search.setOnClickListener(mOnClickListener);
iv_jian.setOnClickListener(mOnClickListener);
iv_jia.setOnClickListener(mOnClickListener);
mIvLocation.setOnClickListener(mOnClickListener);
tv_title_right.setOnClickListener(mOnClickListener);
// mBtSend.setOnClickListener(mOnClickListener);
}
// 地址选择完成
private void selectOk(String path) {
Intent i = new Intent();
PoiItem poiItem = mList.get(mAddressAdapter.getSelectPositon());
i.putExtra("rv_index", poiItem);
try {
if (addStr.equals("")) {
i.putExtra("addStr", poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet());
} else {
i.putExtra("addStr", addStr);
}
} catch (Exception e) {
e.printStackTrace();
i.putExtra("addStr", addStr);
}
i.putExtra("cityStr", cityStr);
i.putExtra("latlonStr", new Gson().toJson(center));
i.putExtra("raduis", radiusJL);
i.putExtra("path", path);
setResult(777, i);
finish();
}
private View.OnClickListener mOnClickListener;
private void drawCirCle(double latitude, double longitude) {
String radiusStr = tv_radius.getText().toString().trim();
radiusStr = radiusStr.substring(0, radiusStr.length() - 1);
mAMap.clear();
center = new LatLng(latitude, longitude);
// 绘制一个圆形
Circle circle = mAMap.addCircle(new CircleOptions().center(center)
.radius(Double.parseDouble(radiusStr)).strokeColor(Const.STROKE_COLOR)
.fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH));
}
/**
* 半径 增加和减少
*/
private void drawCirCleRefresh() {
String radiusStr = tv_radius.getText().toString().trim();
radiusStr = radiusStr.substring(0, radiusStr.length() - 1);
mAMap.clear();
// 绘制一个圆形
Circle circle = mAMap.addCircle(new CircleOptions().center(center)
.radius(Double.parseDouble(radiusStr)).strokeColor(Const.STROKE_COLOR)
.fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH));
}
private void initDatas(Bundle savedInstanceState) {
mMapView.onCreate(savedInstanceState);// 此方法必须重写
mAMap = mMapView.getMap();
mUiSettings = mAMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(false);//是否显示地图中放大缩小按钮
mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
mUiSettings.setScaleControlsEnabled(true);//是否显示缩放级别 比例尺
mUiSettings.setCompassEnabled(true); // 显示指南针
mAMap.setMyLocationEnabled(false);// 是否可触发定位并显示定位层
mList = new ArrayList<>();
mAddressAdapter = new AddressAdapter(this, mList);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAddressAdapter);
gson = new Gson();
// 图标跳动动画
mTransAnimator = ObjectAnimator.ofFloat(mIvCenterLocation, "translationY", 0f, -80f, 0f);
mTransAnimator.setDuration(500);
// mTransAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
}
/**
* 初始化定位
*/
private void initLocation() {
if (null == locationClient) {
//初始化client
locationClient = new AMapLocationClient(this.getApplicationContext());
//设置定位参数
locationClient.setLocationOption(getDefaultOption());
// 设置定位监听
locationClient.setLocationListener(mAMapLocationListener);
}
}
/**
* 默认的定位参数
*/
private AMapLocationClientOption getDefaultOption() {
AMapLocationClientOption mOption = new AMapLocationClientOption();
mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选,设置定位模式,可选的模式有高精度、仅设备、仅网络。默认为高精度模式
mOption.setGpsFirst(false);//可选,设置是否gps优先,只在高精度模式下有效。默认关闭
mOption.setHttpTimeOut(30000);//可选,设置网络请求超时时间。默认为30秒。在仅设备模式下无效
mOption.setInterval(2000);//可选,设置定位间隔。默认为2秒
mOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是true
mOption.setOnceLocation(false);//可选,设置是否单次定位。默认是false
mOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用
AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
mOption.setSensorEnable(false);//可选,设置是否使用传感器。默认是false
mOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差
mOption.setMockEnable(true);//如果您希望位置被模拟,请通过setMockEnable(true);方法开启允许位置模拟
return mOption;
}
private void initPermission() {
// 版本判断。当手机系统大于 23 时,才有必要去判断权限是否获取
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 检查该权限是否已经获取
int i = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]);
int l = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[1]);
int m = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[2]);
int n = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[3]);
// 权限是否已经 授权 GRANTED---授权 DINIED---拒绝
if (i != PackageManager.PERMISSION_GRANTED || l != PackageManager.PERMISSION_GRANTED || m != PackageManager.PERMISSION_GRANTED ||
n != PackageManager.PERMISSION_GRANTED) {
// 如果没有授予该权限,就去提示用户请求
ActivityCompat.requestPermissions(this, permissions, 321);
} else {
startLocation();
}
} else {
startLocation();
}
}
/**
* 开始定位
*/
public void startLocation() {
initLocation();
// 设置定位参数
locationClient.setLocationOption(locationOption);
// 启动定位
locationClient.startLocation();
}
/**
* 停止定位
*/
private void stopLocation() {
if (null != locationClient) {
locationClient.stopLocation();
}
}
/**
* 当定位成功需要做的事情 搜索周边地址信息 启动地图
*/
private void doWhenLocationSucess() {
cityStr = location.getCity();
isSearchData = false;
userSelectPoiItem = DataConversionUtils.changeToPoiItem(location);
if (needMove) {
// doSearchQuery(true, "", location.getCity(), new LatLonPoint(center.latitude,center.longitude));
getAddressInfoByLatLong(center.latitude, center.longitude);
moveMapCamera(center.latitude, center.longitude);
needMove = false;
drawCirCle(center.latitude, center.longitude);
} else {
searchlocation = location;
moveMapCamera(location.getLatitude(), location.getLongitude());
doSearchQuery(true, "", location.getCity(), new LatLonPoint(location.getLatitude(), location.getLongitude()));
drawCirCle(location.getLatitude(), location.getLongitude());
}
// refleshLocationMark(location.getLatitude(), location.getLongitude());
}
/**
* 移动动画
*/
private void startTransAnimator() {
if (null != mTransAnimator && !mTransAnimator.isRunning()) {
mTransAnimator.start();
}
}
/**
* 把地图画面移动到定位地点(使用moveCamera方法没有动画效果)
*
* @param latitude
* @param longitude
*/
private void moveMapCamera(double latitude, double longitude) {
if (null != mAMap) {
mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), zoom));
}
}
/**
* 刷新地图标志物位置
*
* @param latitude
* @param longitude
*/
private void refleshMark(double latitude, double longitude) {
if (mMarker == null) {
mMarker = mAMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
.decodeResource(getResources(), android.R.color.transparent)))
.draggable(true));
}
mMarker.setPosition(new LatLng(latitude, longitude));
// mAMap.invalidate();
}
/**
* 刷新地图标志物gps定位位置
*
* @param latitude
* @param longitude
*/
private void refleshLocationMark(double latitude, double longitude) {
if (mLocationGpsMarker == null) {
mLocationGpsMarker = mAMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
.decodeResource(getResources(), R.mipmap.location_blue)))
.draggable(true));
}
mLocationGpsMarker.setPosition(new LatLng(latitude, longitude));
// mAMap.invalidate();
}
/**
* 刷新地图标志物选中列表的位置
*
* @param latitude
* @param longitude
*/
private void refleshSelectByListMark(double latitude, double longitude) {
if (mSelectByListMarker == null) {
mSelectByListMarker = mAMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
.decodeResource(getResources(), R.mipmap.location_red)))
.draggable(true));
}
mSelectByListMarker.setPosition(new LatLng(latitude, longitude));
if (!mSelectByListMarker.isVisible()) {
mSelectByListMarker.setVisible(true);
}
// mAMap.invalidate();
}
/**
* 开始进行poi搜索
*
* @param isReflsh 是否为刷新数据
* @param keyWord
* @param city
* @param lpTemp
*/
protected void doSearchQuery(boolean isReflsh, String keyWord, String city, LatLonPoint lpTemp) {
mQuery = new PoiSearch.Query(keyWord, "", city);//第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国)
mQuery.setPageSize(30);// 设置每页最多返回多少条poiitem
if (isReflsh) {
searchNowPageNum = 0;
} else {
searchNowPageNum++;
}
if (searchNowPageNum > searchAllPageNum) {
return;
}
mQuery.setPageNum(searchNowPageNum);// 设置查第一页
mPoiSearch = new PoiSearch(this, mQuery);
mOnPoiSearchListener.IsReflsh(isReflsh);
mPoiSearch.setOnPoiSearchListener(mOnPoiSearchListener);
if (lpTemp != null) {
mPoiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 10000, true));//该范围的中心点-----半径,单位:米-----是否按照距离排序
}
mPoiSearch.searchPOIAsyn();// 异步搜索
}
/**
* 通过经纬度获取当前地址详细信息,逆地址编码
*
* @param latitude
* @param longitude
*/
private void getAddressInfoByLatLong(double latitude, double longitude) {
GeocodeSearch geocodeSearch = new GeocodeSearch(this);
/*
point - 要进行逆地理编码的地理坐标点。
radius - 查找范围。默认值为1000,取值范围1-3000,单位米。
latLonType - 输入参数坐标类型。包含GPS坐标和高德坐标。 可以参考RegeocodeQuery.setLatLonType(String)
*/
RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(latitude, longitude), 3000, GeocodeSearch.AMAP);
geocodeSearch.getFromLocationAsyn(query);
geocodeSearch.setOnGeocodeSearchListener(mOnGeocodeSearchListener);
}
private void showToastWithErrorInfo(int error) {
String tips = "定位错误码:" + error;
switch (error) {
case 4:
tips = "请检查设备网络是否通畅,检查通过接口设置的网络访问超时时间,建议采用默认的30秒。";
break;
case 7:
tips = "请仔细检查key绑定的sha1值与apk签名sha1值是否对应。";
break;
case 12:
tips = "请在设备的设置中开启app的定位权限。";
break;
case 18:
tips = "建议手机关闭飞行模式,并打开WIFI开关";
break;
case 19:
tips = "建议手机插上sim卡,打开WIFI开关";
break;
}
Toast.makeText(MapActivity.this.getApplicationContext(), tips, Toast.LENGTH_LONG).show();
}
//重写Poi搜索监听器,可扩展上拉加载数据,下拉刷新
class onPoiSearchLintener implements PoiSearch.OnPoiSearchListener {
private boolean isReflsh;//是为下拉刷新,否为上拉加载更多
public void IsReflsh(boolean isReflsh) {
this.isReflsh = isReflsh;
}
@Override
public void onPoiSearched(PoiResult result, int i) {
if (i == 1000) {
if (result != null && result.getQuery() != null) {// 搜索poi的结果
searchAllPageNum = result.getPageCount();
if (result.getQuery().equals(mQuery)) {// 是否是同一条
if (isReflsh && null != mList) {
mList.clear();
if (null != userSelectPoiItem) {
mList.add(0, userSelectPoiItem);
}
}
mList.addAll(result.getPois());// 取得第一页的poiitem数据,页数从数字0开始
if (null != mAddressAdapter) {
mAddressAdapter.setList(mList);
mRecyclerView.smoothScrollToPosition(0);
}
}
}
}
}
@Override
public void onPoiItemSearched(PoiItem poiItem, int i) {
}
}
/**
* 用户权限 申请 的回调方法
*
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 321) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
//如果没有获取权限,那么可以提示用户去设置界面--->应用权限开启权限
Toast toast = Toast.makeText(this, "请开启权限", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
//获取权限成功
startLocation();
}
}
}
}
/**
* 截屏时回调的方法。
*
* @param bitmap 调用截屏接口返回的截屏对象。
*/
@Override
public void onMapScreenShot(Bitmap bitmap) {
}
/**
* 带有地图渲染状态的截屏回调方法。
* 根据返回的状态码,可以判断当前视图渲染是否完成。
*
* @param bitmap 调用截屏接口返回的截屏对象。
* @param arg1 地图渲染状态, 1:地图渲染完成,0:未绘制完成
*/
@Override
public void onMapScreenShot(Bitmap bitmap, int arg1) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
if (null == bitmap) {
return;
}
File fold = new File(Environment.getExternalStorageDirectory() + "/ant/");
if (!fold.exists()) {
fold.mkdirs();
}
try {
String path = Environment.getExternalStorageDirectory() + "/ant/test_" +
sdf.format(new Date()) + ".png";
File f = new File(path);
if (!f.exists()) {
f.createNewFile();
}
FileOutputStream fos = new FileOutputStream(path);
boolean b = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
try {
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer buffer = new StringBuffer();
if (b) {
dismissYDialog();
selectOk(path);
buffer.append("截屏成功 ");
} else {
buffer.append("截屏失败 ");
}
if (arg1 != 0) {
buffer.append("地图渲染完成,截屏无网格");
} else {
buffer.append("地图未渲染完成,截屏有网格");
}
// ToastUtil.show(ScreenShotActivity.this, buffer.toString());
LogUtil.e(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private int getBILICHILong(int zoom) {
switch (zoom) {
case 18:
return 25;
case 15:
return 200;
case 16:
return 100;
case 17:
return 50;
case 14:
return 400;
case 13:
return 1000;
case 12:
return 2000;
case 11:
return 5000;
}
return 1;
}
}