亲测代码-web js以此类推
1.俩点取中点,算角度箭头
2.画轨迹线不在点上,[
anchor(0.5f,0.5f)
]
3.算距离
package com.test.smartwater.add;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.test.das.FeeUtil;
import com.test.des.DateUtil;
import com.test.devicemanage.util.StringUtil;
import com.test.smartwater.BuildConfig;
import com.test.smartwater.R;
import com.test.smartwater.activity.ListFlowAct;
import com.test.smartwater.activity.ListPressureAct;
import com.test.smartwater.activity.ListWaterLevelAct;
import com.test.smartwater.activity.ListWaterQualityAct;
import com.test.smartwater.activity.PayoutActivity;
import com.test.smartwater.base.BaseActivity;
import com.test.smartwater.base.SWApplication;
import com.test.smartwater.business.MonitorBusiness;
import com.test.smartwater.entity.WaterRegimen;
import com.test.smartwater.util.Contants;
import com.test.smartwater.util.HttpUtil;
import com.test.smartwater.util.LogUtil;
import com.test.smartwater.util.Logi;
import com.google.gson.JsonObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 查看轨迹
* by2022.2.16
*/
public class InspectionRouteMapAct extends BaseActivity {
private MapView mapView;
private BaiduMap mBaiduMap;
LocationClient mLocClient;
boolean isFirstLoc = true; // 是否首次定位
LatLng bdLat;
List<WaterRegimen> regimenList=new ArrayList<>();
List<JSONObject> listJSONObject=new ArrayList<>();
private String locLat;
private String locLon;
private String addr;
private AlertDialog dialog;
private ScheduledExecutorService executorService;
private Spinner spinner_abc;
private CustomSpinnerAdapter adapter_abc;
private int type;
private String selecttype="";
private boolean isDrawPoint=false;
TextView et_start, et_end;
String psnid;
String dateStyle = "yyyy-MM-dd HH:mm";
View bottomView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.inspectionroute_baidumap);
executorService = Executors.newScheduledThreadPool(1);
type=getIntent().getIntExtra("type",0);
setTitleOnly("查看轨迹");
initSpinner();
initDate();
// downloadData("PR");
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 查询接口
* @throws Exception
*/
private void initDate() throws Exception {
LinearLayout ll_bottom = (LinearLayout) findViewById(R.id.ll_bottom);
if (bottomView == null) {
bottomView = View.inflate(this, R.layout.date_select_layout, null);
ll_bottom.addView(bottomView);
}
//开始时间
et_start = bottomView.findViewById(R.id.et_start);
//结束时间
et_end = bottomView.findViewById(R.id.et_end);
//获取当前的时间
String date = com.test.smartwater.util.StringUtil.getDatetime(dateStyle);
String endDate = com.test.smartwater.util.StringUtil.getCusDate(date, dateStyle, Calendar.HOUR, 0);
//3*24个小时以前
String startDate = com.test.smartwater.util.StringUtil.getCusDate(date, dateStyle, Calendar.HOUR, -24*7);
startDate = DateUtil.DateBeforeNow(0)+" 00:00:00";
et_end.setText(endDate);
et_start.setText(startDate);
et_start.setOnClickListener(onClickListener);
et_end.setOnClickListener(onClickListener);
//查询按钮
bottomView.findViewById(R.id.bt_search).setOnClickListener(onClickListener);
}
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.et_start:
com.test.smartwater.util.StringUtil.showCustomDatePicker(InspectionRouteMapAct.this, dateStyle, true, et_start);
break;
case R.id.et_end:
com.test.smartwater.util.StringUtil.showCustomDatePicker(InspectionRouteMapAct.this, dateStyle, true, et_end);
break;
case R.id.bt_search://查询
downloadData();
break;
}
}
};
double firstX=0;
double firstY=0;
/*
* 地图初始化
**/
private void initMap() {
try{
double gpsX=0.0f;
double gpsY=0.0f;
//寿光市地理坐标
if(BuildConfig.testNAME.equalsIgnoreCase("PZH")) {
gpsX = Double.parseDouble("101.718369");
gpsY = Double.parseDouble("26.58498");
}else if(BuildConfig.testNAME.equalsIgnoreCase("YCDF")) {
setTitleOnly("地图监控");//大丰区自来水有限公司
gpsX =firstX;
gpsY = firstY;
if(gpsY==0){
//有时候服务器请求不到数据 那么我就默认大丰的
gpsX = Double.parseDouble("120.448913");
gpsY = Double.parseDouble("33.204275");
}
}else{
gpsX = Double.parseDouble("118.79098");
gpsY = Double.parseDouble("36.85541");
}
LatLng gpsLat = new LatLng(gpsY, gpsX);
//gps 坐标转换成百度坐标
bdLat = convertToBaidu09Coord(gpsLat);
mapView = (MapView) findViewById(R.id.bmapView);
mBaiduMap = mapView.getMap();
mBaiduMap.setMyLocationEnabled(true);
//by jiaxi 地图俯视
mBaiduMap.getUiSettings().setOverlookingGesturesEnabled(false);
//by jiaxi Rotate
mBaiduMap.getUiSettings().setRotateGesturesEnabled(false);
LatLng cenpt = new LatLng(bdLat.latitude, bdLat.longitude);// 以站点位置为中心
//由9倍放到11倍
final MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(14).build();
MapStatusUpdate msu = MapStatusUpdateFactory.newMapStatus(mMapStatus);
mBaiduMap.setMapStatus(msu);
mBaiduMap.setMaxAndMinZoomLevel(21, 4);
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(bdLocationListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);
option.setIsNeedAddress(true);
mLocClient.setLocOption(option);
mLocClient.start();
//标记站点的位置
if(mBaiduMap!=null){
//暂时不需要 点击点弹出view by2022.2.17
mBaiduMap.setOnMarkerClickListener(stationMarkerListener);
}
}catch (Exception e){isDrawPoint=false;
e.printStackTrace();
}
}
BaiduMap.OnMarkerClickListener stationMarkerListener= new BaiduMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
if (marker != null) {
Bundle bundle = marker.getExtraInfo();
if (bundle != null) {
LatLng ll = marker.getPosition();
View view = pointOperateDialog(bundle, ll);
InfoWindow mInfoWindow = new InfoWindow(view, ll, -40);
mBaiduMap.showInfoWindow(mInfoWindow);
}
}else{
Logi.i("可能是箭头 所有不用显示");
}
return false;
}
};
private View pointOperateDialog(final Bundle bundle, final LatLng targetLat) {
LayoutInflater inflater = LayoutInflater.from(InspectionRouteMapAct.this);
View view = inflater.inflate(R.layout.monitor_mark_item, null);
try{
String tmp= (String) bundle.getSerializable("regimeninfo");
JSONObject info =new JSONObject(tmp);
// Logi.i("pointOperateDialog"+info);
TextView tv_code = (TextView) view.findViewById(R.id.tv_code);
tv_code.setText(""+info.getString("CreateTime"));
TextView tv_codename = (TextView) view.findViewById(R.id.tv_codename);
tv_codename.setText("时间");
TextView tv_first = (TextView) view.findViewById(R.id.tv_first);
float ac= new BigDecimal(info.getString("AccuRacy")).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
tv_first.setText(""+ac);
TextView tv_firstname = (TextView) view.findViewById(R.id.tv_firstname);
tv_firstname.setText("精度");
// TextView tv_secord = (TextView) view.findViewById(R.id.tv_secord);
// tv_secord.setText(""+info.getString("CreateTime"));
// TextView tv_secordname = (TextView) view.findViewById(R.id.tv_secordname);
// tv_secordname.setText("经纬度");
// //详情
// view.findViewById(com.test.devicemanage.R.id.bt_detail).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View arg0) {
// mBaiduMap.hideInfoWindow();
// if(info.getStationType()!=null) {
// if (info.getStationType() .equals("压力")) {
// Intent intent = new Intent(InspectionRouteMapAct.this, ListPressureAct.class);
// intent.putExtra("id", info.getId());
// intent.putExtra("name", info.getName());
// intent.putExtra("type", info.getStationType());
// startActivity(intent);
// } else if (info.getStationType() .equals("流量")) {
// Intent intent = new Intent(InspectionRouteMapAct.this, ListFlowAct.class);
// intent.putExtra("id", info.getId());
// intent.putExtra("name", info.getName());
// intent.putExtra("type", info.getStationType());
// startActivity(intent);
// } else if (info.getStationType() .equals("水位")) {
// Intent intent = new Intent(InspectionRouteMapAct.this, ListWaterLevelAct.class);
// intent.putExtra("id", info.getId());
// intent.putExtra("name", info.getName());
// intent.putExtra("type", info.getStationType());
// startActivity(intent);
// } else if(info.getStationType() .equals("水质")){
// Intent intent = new Intent(InspectionRouteMapAct.this, ListWaterQualityAct.class);
// intent.putExtra("id", info.getId());
// intent.putExtra("name", info.getName());
// intent.putExtra("type", info.getStationType());
// startActivity(intent);
// }
// }
// }
// });
//导航
view.findViewById(com.test.devicemanage.R.id.bt_navi).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mBaiduMap.hideInfoWindow();
if (!("".equals(locLon) && "".equals(locLat))) {//定位到当前位置信息,可以进行导航
//start 起点坐标,targetLat 目的地坐标
LatLng start = new LatLng(Double.parseDouble(locLat), Double.parseDouble(locLon));
NaviParaOption para = new NaviParaOption().startPoint(start).endPoint(targetLat);
try {
BaiduMapNavigation.openBaiduMapNavi(para, InspectionRouteMapAct.this);
} catch (BaiduMapAppNotSupportNaviException e) {
e.printStackTrace();
showConfirmDialog(InspectionRouteMapAct.this, "温馨提示", "您尚未安装百度地图app或app版本过低,点击确认安装?", "确定","取消",3, null);
}
} else {
//网络或者GPS信号不好,没有定到当前位置信息。进行弹框提示
StringUtil.Toast(InspectionRouteMapAct.this, "当前网络信号较差,没有定位到所在位置,无法导航");
}
}
});
}catch (Exception e){
Logi.e(e);
}
//关闭弹框
view.findViewById(com.test.devicemanage.R.id.bt_close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mBaiduMap.hideInfoWindow();
}
});
return view;
}
@Override
public void dialog_confim(int what, Bundle data) {
super.dialog_confim(what, data);
if (what == 3) {//百度地图安装提示
OpenClientUtil.getLatestBaiduMapApp(InspectionRouteMapAct.this);
}
}
@Override
public void dialog_cancel(int what, Bundle data) {
super.dialog_cancel(what, data);
if(what==3) {
mBaiduMap.hideInfoWindow();
}
}
List<ArrayList<JSONObject>> listTime = new ArrayList<ArrayList<JSONObject>>();
//转换好的
Bitmap bitmapView;
Bitmap bitmapViewEnd;
Bitmap bitmapViewStart;
BitmapDescriptor bitmapViewDescriptor;
BitmapDescriptor bitmapViewEndBitmapDescriptor;
BitmapDescriptor bitmapViewStartDescriptor;
//为了节省内存 将8个方向都加载一下
ArrayList<BitmapDescriptor> listArrow=new ArrayList<>();
ArrayList<Bitmap> listArrowBitmap=new ArrayList<>();
private int[] array_id_arrow = {
R.layout.custom_lbs_big,
R.layout.custom_lbs_big7,
R.layout.custom_lbs_big6,
R.layout.custom_lbs_big5,
R.layout.custom_lbs_big4,
R.layout.custom_lbs_big3,
R.layout.custom_lbs_big2,
R.layout.custom_lbs_big1};
//实例化多少按钮出来 40个效果
private int array_max_total=40;
//每一个多少度
private int array_max_percent=360/array_max_total;
/**
* 将点显示出来
* @throws Exception
*/
private void drawPoint() throws Exception{
isDrawPoint=true;
mBaiduMap.clear();
ImageView lay_bg;
View view; Bitmap bitmapTmp;
//开始实例化bitmap
// 园点
view = LayoutInflater.from(this).inflate(R.layout.custom_lbs_pop, null);
lay_bg = view.findViewById(R.id.img_bg);
//暂时不显示点
// lay_bg.setImageResource(R.drawable.icon_all_null);
lay_bg.setImageResource(R.drawable.icon_all_blue);
bitmapView=changeView2Drawble(view,null);
bitmapViewDescriptor = BitmapDescriptorFactory.fromBitmap(bitmapView);
//启动点
view = LayoutInflater.from(this).inflate(R.layout.custom_lbs_pop, null);
lay_bg = view.findViewById(R.id.img_bg);
lay_bg.setImageResource(R.drawable.icon_all_green);
bitmapViewStart=changeView2Drawble(view,null);
bitmapViewStartDescriptor = BitmapDescriptorFactory.fromBitmap(bitmapViewStart);
//结束点
view = LayoutInflater.from(this).inflate(R.layout.custom_lbs_pop, null);
lay_bg = view.findViewById(R.id.img_bg);
lay_bg.setImageResource(R.drawable.icon_all_red);
bitmapViewEnd=changeView2Drawble(view,null);
bitmapViewEndBitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmapViewEnd);
//结束实例化bitmap
listArrow.clear();
listArrowBitmap.clear();
Bitmap bitmapUser;
//将所有箭头放入
for(int i=0;i<array_max_total;i++){
view= LayoutInflater.from(this).inflate(R.layout.custom_lbs_big, null);
ViewGroup tmp= (ViewGroup) view;
//取第一个图片
ImageView imageView=(ImageView)tmp.getChildAt(0);
//旋转
if(i==0){
imageView.setRotation(0);
}else{
imageView.setRotation(360-i*array_max_percent);
}
bitmapUser=changeView2Drawble(view,null);
listArrow.add(BitmapDescriptorFactory.fromBitmap(bitmapUser));;
listArrowBitmap.add(bitmapUser);
}
//第一步 将所有点 如果超过5分钟则 分组
int max_sec=5*60;
listTime.clear();
String endtime="";
// bitmapicon_arrow=BitmapFactory.decodeResource(getResources(),R.drawable.icon_arrow);
ArrayList<JSONObject> listTmp=new ArrayList<>();
Collections.reverse(listJSONObject);
//取5位数据 ,假如前面
//是否进行分段了
boolean isOverView=false;
JSONObject finalJsonObject=null;
for(int i=0;i<listJSONObject.size();i++) {
JSONObject info=listJSONObject.get(i);
String string=info.getString("CreateTime");
if("".equals(string)){
continue;
}else if(i==0){
finalJsonObject=info;
endtime=string;
continue;
} else{//剔除掉俩个经纬度8位相同的值
if(com.test.smartwater.util.StringUtil.getGpsCHECK(info,finalJsonObject)){
// Logi.i("repeact>"+info.getString("CreateTime"));
continue;
} finalJsonObject=info;
//时间间隔
long limit=DateUtil.getDistanceTimes(string,endtime);
// Logi.i(""+string+" limit:"+limit+" \t max_sec:"+"isOverView:"+isOverView);
endtime=string;
//小于约定
if(limit>max_sec&&listTmp.size()!=0){
listTime.add(listTmp);isOverView=true;
listTmp=new ArrayList<>();
}else {
isOverView=false;
}
listTmp.add(info);
}
}
//只有一条数据
listTime.add(listTmp);
for(int i=0;i<listTime.size();i++){
List<JSONObject> listJSON=listTime.get(i);
Logi.i("一共"+listTime.size()+"组(当前第"+(i+i)+"组) \t 当前组第一次:first_CreateTime:"+listJSON.get(0).getString("CreateTime"));
checkLinePoint(listJSON);
}
isDrawPoint=false;
}
public void checkLinePoint(List<JSONObject> listData ) throws Exception{
List<LatLng> points = new ArrayList<LatLng>();
JSONObject lastObject=null;
for(int i=0;i<listData.size();i++) {
JSONObject jsonObject=listData.get(i);
double gpsX=Double.parseDouble(jsonObject.getString("PointX"));
double gpsY =Double.parseDouble(jsonObject.getString("PointY"));
if(!"".equals(gpsY)) {
if(gpsX!=0.0f || gpsY!=0.0f) {
LatLng gpsLat = new LatLng(gpsY, gpsX);
//gps 坐标转换成百度坐标
LatLng bdLat = convertToBaidu09Coord(gpsLat);
if(lastObject!=null){
//将当前坐标和上一个坐标 取得中间
double gpsXlastObject=Double.parseDouble(lastObject.getString("PointX"));
double gpsYlastObject =Double.parseDouble(lastObject.getString("PointY"));
double lntesta = (Math.max(gpsYlastObject,gpsY)-Math.min(gpsYlastObject,gpsY))/2;
double latca = (Math.max(gpsXlastObject,gpsX)-Math.min(gpsXlastObject,gpsX))/2;
double lntestenter = Math.min(gpsYlastObject,gpsY)+lntesta;
double latcenter = Math.min(gpsXlastObject,gpsX)+latca;
double orientationDegree=0;
orientationDegree= getAngleNew(gpsXlastObject,gpsYlastObject,gpsX,gpsY);
//计算出角度 然后将预制的图片放进去[很多轨迹时候,不能通过bitmap旋转 这样耗内存 或者image.set旋转]
int angel= (int) orientationDegree;;
//每一个图片大约面积
int angel_index=angel/array_max_percent;
Logi.i("CreateTime:"+jsonObject.getString("CreateTime")+"\t current:"+gpsX+","+gpsY+" \t center:"+latcenter+" \t angel_index:"+angel_index+"\t angel:"+angel);
LatLng new_gpsLat = new LatLng(lntestenter, latcenter);
//gps 坐标转换成百度坐标
LatLng new_bdLat = convertToBaidu09Coord(new_gpsLat);
BitmapDescriptor bitmap=null;
for(int c=0;c<listArrow.size();c++){
//将所有的方向加载出来
if(c==angel_index){
bitmap=listArrow.get(c);
}
}
long l=System.currentTimeMillis();
Bundle bundle = new Bundle();
//为了点击时候 不进行弹框(箭头不弹窗)
bundle=null;
OverlayOptions ooB = new MarkerOptions().position(new_bdLat).anchor(0.5f,0.5f).icon(bitmap).zIndex(9).draggable(true).extraInfo(bundle);
mBaiduMap.addOverlay(ooB);
}
points.add(bdLat);
Logi.i("checkLinePoint>>"+i);
// jsonObject.getString("bd_x",bdLat.+"")
//俩点之间获取中间节点
Bundle bundle = new Bundle();
bundle.putSerializable("regimeninfo", ""+jsonObject);
BitmapDescriptor bp=null;
if(i==0){
//开始
bp=bitmapViewStartDescriptor;
}else if(i==listData.size()-1){
//最后一行的时候
bp=bitmapViewEndBitmapDescriptor;
}else{
//正常加载
bp=bitmapViewDescriptor;
}
// anchor 轨迹点居中
OverlayOptions ooB = new MarkerOptions().anchor(0.5f,0.5f).position(bdLat).icon(bp).zIndex(9).draggable(true).extraInfo(bundle);
mBaiduMap.addOverlay(ooB);
lastObject=jsonObject;
}
}
}
//回收
if(bitmapView!=null){
bitmapView.recycle();
}
if(bitmapViewEnd!=null){
bitmapViewEnd.recycle();
}
if(bitmapViewStart!=null){
bitmapViewStart.recycle();
}
if(listArrowBitmap!=null){
for(Bitmap bitmap:listArrowBitmap){
if(bitmap!=null){
bitmap.recycle();
}
}
}
//开始划线条https://lbsyun.baidu.com/index.php?title=androidsdk/guide/render-map/ployline
// //构建折线点坐标
// 设置折线的属性
if (points.size()>=2){
//必须大于2个点就划线吧
OverlayOptions mOverlayOptions = new PolylineOptions()
.width(7)
.color(0xAAFF0000)
.points(points);
// Logi.i("points>>"+points.size());
//在地图上绘制折线
//mPloyline 折线对象
Overlay mPolyline = mBaiduMap.addOverlay(mOverlayOptions);
}
}
BDLocationListener bdLocationListener = new BDLocationListener() {
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null || mapView == null) {
return;
}
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(100).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
mBaiduMap.setMyLocationData(locData);
locLon = String.valueOf(location.getLongitude());
locLat = String.valueOf(location.getLatitude());
addr = location.getAddrStr();
if (isFirstLoc) {
isFirstLoc = false;
// LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
// MapStatus.Builder builder = new MapStatus.Builder();
// builder.target(ll).zoom(15.0f);
// mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
}
}
};
/**
* Gps 坐标 转 百度坐标
*/
public LatLng convertToBaidu09Coord(LatLng source) {
CoordinateConverter cc = new CoordinateConverter();
return cc.from(CoordinateConverter.CoordType.GPS).coord(source).convert();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK) {
if(isDrawPoint){
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mLocClient != null) {
mLocClient.registerLocationListener(bdLocationListener);
mLocClient.stop();
}
if (mapView != null) {
// 关闭定位图层
mBaiduMap.setMyLocationEnabled(false);
mBaiduMap.clear();
mapView.removeAllViews();
mapView.onDestroy();
mapView = null;
}
if(regimenList!=null){
regimenList.clear();
}
}
public String createJson(String type) {
JSONObject obj = new JSONObject();
try {
SWApplication application = (SWApplication) this.getApplication();
String id = application.getUser().getId();
String starttime="";
String endtime="";
starttime=et_start.getText()+"";
endtime=et_end.getText()+"";
// 陈星宇
// id="1893436970841";
// starttime=DateUtil.DateBeforeNow(-1)+" 10:02:00";
// endtime=DateUtil.DateBeforeNow(-1)+" 10:28:00";
obj.put("taskId", "");
obj.put("userId", id);
obj.put("startTime", starttime);
obj.put("endTime", endtime);
} catch (JSONException e) {
e.printStackTrace();
}
return obj.toString();
}
private void downloadData(){
// edit_search.setText("");
// findList.clear();
dialog = showProgressDialog(this,"正在下载..");
dialog.show();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
Message msg = new Message();
try {
String params = createJson(selecttype);
String result = HttpUtil.getInstance().http_post_json(InspectionRouteMapAct.this, Contants.getInstance().GetInspectionRoute, params, "");
if (!result.equals("")) {
List<JSONObject> list = MonitorBusiness.getInstance().parseJsonObjectData(result);
listJSONObject.clear();
if (list != null) {
if (list.size() > 0) {
listJSONObject.addAll(list);
list.clear();
}
msg.obj = "共有 " + listJSONObject.size() + " 条数据";
msg.what = 2;
} else {
msg.obj = "查询异常";
msg.what = 1;
}
} else {
listJSONObject.clear();
msg.what = 1;
msg.obj = "连接异常";
}
} catch (Exception e) {
e.printStackTrace();
LogUtil log = new LogUtil(e);
listJSONObject.clear();
if (e instanceof ConnectException || e instanceof SocketTimeoutException) {
msg.obj = "网络连接异常";
} else if (e instanceof JSONException) {
msg.obj = "JSON 解析异常";
} else {
msg.obj = "服务异常";
}
msg.what = 1;
}
if (handler != null) {
handler.sendMessage(msg);
}
}
},0,300, TimeUnit.SECONDS);//zhouxd test
}
Handler handler = new Handler() {
@Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
switch (msg.what) {
case 1:
// adapter.notifyDataSetChanged();
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
clearMap();
//不用去显示2022.2.17
if (msg.obj != null) {
StringUtil.Toast(InspectionRouteMapAct.this, msg.obj.toString());
}
break;
case 2:
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
initJsonMap();
// if (msg.obj != null) {
// StringUtil.Toast(AllStationPlaceMapAct.this, msg.obj.toString());
// }
// handler.post(new Runnable() {
// @Override
// public void run() {
// drawPoint();
// }
// });
break;
case 3:
// if (dialog != null && dialog.isShowing()) {
// dialog.dismiss();
// }
// showNoticeDialog(InspectionRouteMapAct.this, "提示框",msg.obj.toString(),4);
break;
}
}
};
public void initJsonMap(){
try{
if(0==listJSONObject.size()){
//当没有数据的时候
clearMap();
return ;
}
//取中间的gps作为居中
int middle=listJSONObject.size()/2;
JSONObject jsonObject=listJSONObject.get(middle);
firstX=Double.parseDouble(jsonObject.getString("PointX"));
firstY=Double.parseDouble(jsonObject.getString("PointY"));
initMap();
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(200);
//这里画点
drawPoint();
}catch (Exception e){
//方便返回按钮返回
isDrawPoint=false;
Logi.e(e);
}
}
}).start();
}catch (Exception e){
Logi.e(e);
//方便返回按钮返回
isDrawPoint=false;
}
initMap();
}
private void clearMap(){
try{
mBaiduMap.clear();
}catch (Exception e){
Logi.e(e);
//方便返回按钮返回
isDrawPoint=false;
}
}
private Bitmap changeView2Drawble(View view,JSONObject jsonObject) throws Exception {
view.setDrawintestacheEnabled(true);
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0,
view.getMeasuredWidth(),
view.getMeasuredHeight());
view.buildDrawintestache();
//获取到图片,这样就可以添加到Map上
Bitmap bitmap = Bitmap.createBitmap(view.getDrawintestache());
return bitmap;
}
public Bitmap bitmapRotation(Bitmap bm, final int orientationDegree) {
//xiaolv dixia
Matrix m = new Matrix();
m.setRotate(orientationDegree, (float) bm.getWidth() / 2,
(float) bm.getHeight() / 2);
float targetX, targetY;
if (orientationDegree == 90) {
targetX = bm.getHeight();
targetY = 0;
} else if (orientationDegree == 270) {
targetX = 0;
targetY = bm.getWidth();
} else {
targetX = bm.getHeight();
targetY = bm.getWidth();
}
final float[] values = new float[9];
m.getValues(values);
float x1 = values[Matrix.MTRANS_X];
float y1 = values[Matrix.MTRANS_Y];
m.postTranslate(targetX - x1, targetY - y1);
Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(),
Bitmap.Config.ARGB_8888);
Paint paint = new Paint();
Canvas canvas = new Canvas(bm1);
canvas.drawBitmap(bm, m, paint);
return bm1;
}
// /*
// **把自定义的布局文件转成Bitmap
// */
// private Bitmap changeView2Drawble(String type,String state,String alarmColor,String value, String name) {
// View view = LayoutInflater.from(this).inflate(R.layout.custom_bd_pop, null);
// TextView tv_value = view.findViewById(R.id.tv_value);
// TextView tv_name = view.findViewById(R.id.tv_name);
// ImageView lay_bg = view.findViewById(R.id.img_bg);
// if(type!=null&&state.equals("正常")) {
// if (type.equals("压力")){
// lay_bg.setBackgroundResource(R.drawable.ic_pr);
// }else if (type.equals("流量")){
// lay_bg.setBackgroundResource(R.drawable.ic_fl);
// }else if (type.equals("水位")){
// lay_bg.setBackgroundResource(R.drawable.ic_wl);
// }else if (type.equals("水质")){
// lay_bg.setBackgroundResource(R.drawable.ic_wq);
// }else{
// lay_bg.setBackgroundResource(R.drawable.icon_green);
// }
// }else{
// lay_bg.setBackgroundResource(R.drawable.ic_alarm);
// }
// if(StringUtil.isEmpty(alarmColor)) {
// tv_value.setTextColor(getResources().getColor(R.color.black));
// tv_name.setTextColor(getResources().getColor(R.color.black));
// }else{
// tv_value.setTextColor(Color.parseColor(alarmColor));
// tv_name.setTextColor(Color.parseColor(alarmColor));
// }
// tv_value.setText(value);
// tv_name.setText(name);//文字过长可以做处理
// view.setDrawintestacheEnabled(true);
// view.measure(
// View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
// View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
// view.layout(0, 0,
// view.getMeasuredWidth(),
// view.getMeasuredHeight());
// view.buildDrawintestache();
// //获取到图片,这样就可以添加到Map上
// Bitmap bitmap = Bitmap.createBitmap(view.getDrawintestache());
// return bitmap;
// }
//暂时无用,所以隐藏by2022.2.16
private void initSpinner(){
TextView tv_spinner=(TextView)findViewById(R.id.tv_spinner);
tv_spinner.setVisibility(View.VISIBLE);
spinner_abc =(Spinner) findViewById(R.id.spinner_abc);
spinner_abc.setVisibility(View.VISIBLE);
//暂时无用,所以隐藏by2022.2.16
tv_spinner.setVisibility(View.GONE);
spinner_abc.setVisibility(View.GONE);
List<Map<String,Object>> abclist = new ArrayList<>();
// Map<String,Object> map0=new HashMap<>();
// map0.put("sp_key","");
// map0.put("sp_value","--请选择--");
// abclist.add(map0);
if(BuildConfig.testNAME.equalsIgnoreCase("DF")) {
Map<String, Object> map1 = new HashMap<>();
map1.put("sp_key", "PR");
map1.put("sp_value", "压力");
abclist.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("sp_key", "FL");
map2.put("sp_value", "流量");
abclist.add(map2);
Map<String, Object> map4 = new HashMap<>();
map4.put("sp_key", "WQ");
map4.put("sp_value", "水质");
abclist.add(map4);
}else {
Map<String, Object> map1 = new HashMap<>();
map1.put("sp_key", "PR");
map1.put("sp_value", "压力");
abclist.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("sp_key", "FL");
map2.put("sp_value", "流量");
abclist.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("sp_key", "WL");
map3.put("sp_value", "水位");
abclist.add(map3);
Map<String, Object> map4 = new HashMap<>();
map4.put("sp_key", "WQ");
map4.put("sp_value", "水质");
abclist.add(map4);
}
adapter_abc = new CustomSpinnerAdapter(InspectionRouteMapAct.this,1, abclist,spinner_abc);
spinner_abc.setAdapter(adapter_abc);
spinner_abc.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String sp_key=(String) abclist.get(position).get("sp_key");
selectSpinner(sp_key);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner_abc.setSelection(type,false);
}
private void selectSpinner(String sp_key){
selecttype=sp_key;
switch (sp_key){
case "PR":
downloadData();
break;
case "FL":
downloadData();
break;
case "WL":
downloadData();
break;
case "WQ":
downloadData();
break;
default:
break;
}
}private double getAngleNew(double firstPoint_lat, double firstPoint_lng, double nextPoint_lat, double nextPoint_lng) {
if ((firstPoint_lat ==0)||(nextPoint_lat ==0)) {
return 0;
}
// double slope = [self getSlopWithFromCoord:fromCoord toCoord:toCoord];
//
// if (slope == MAXFLOAT) {
// if (toLat > fromLat) {
// return 0;
// } else {
// return 180;
// }
// }
// double toLat = nextPoint_lng;
// double tolon = nextPoint_lat;
//
//
// double radio = Math.atan(slope);
// double angle = 180 * (radio / Math.PI);
// if (slope > 0) {
// if (tolon < fromlon) {
// angle = -90 - angle;
// } else {
// angle = 90 - angle;
// }
// } else if (slope == 0) {
// if (tolon < fromlon) {
// angle = -90;
// } else {
// angle = 90;
// }
// } else {
// if (toLat < fromLat) {
// angle = 90 - angle;
// } else {
// angle = -90 - angle;
// }
// }
// return angle;
double dRotateAngle = Math.atan2(
Math.abs(firstPoint_lng - nextPoint_lng),
Math.abs(firstPoint_lat - nextPoint_lat)
);
if (nextPoint_lng >= firstPoint_lng) {
if (nextPoint_lat >= firstPoint_lat) {
} else {
dRotateAngle = Math.PI - dRotateAngle;
}
} else {
if (nextPoint_lat >= firstPoint_lat) {
dRotateAngle = 2 * Math.PI - dRotateAngle;
} else {
dRotateAngle = Math.PI + dRotateAngle;
}
}
dRotateAngle = (dRotateAngle * 180) / Math.PI;
return dRotateAngle;
}
/**
* 以正向x轴为角度
* @param lat_a 纬度1
* @param lng_a 经度1
* @param lat_b 纬度2
* @param lng_b 经度2
* @return
*/
private double getAngle1(double lat_a, double lng_a, double lat_b, double lng_b) {
double y = Math.sin(lng_b-lng_a) * Math.cos(lat_b);
double x = Math.cos(lat_a)*Math.sin(lat_b) - Math.sin(lat_a)*Math.cos(lat_b)*Math.cos(lng_b-lng_a);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
Logi.i("getAngle1 realy:"+lat_a+">>Angle>"+brng);
// if(brng<0&&brng>-0.5){
// return brng;
// }
if(brng < 0){
brng = brng +360;
}
// //by jiaxi
// if(brng>45&brng<180){
// brng=brng +180;
// //补一下角度
// }else if(brng>270&brng<360){
// brng=brng -180;
// //补一下角度
// }
// if(brng>=360){
// brng=0;
// }
return brng;
}
}
|