<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/address_select_item_ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:gravity="center_vertical"
android:minHeight="@dimen/dp_50"
android:orientation="horizontal"
android:paddingHorizontal="10dp"
android:paddingVertical="@dimen/dp_12">
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="@dimen/dp_10"
android:layout_weight="1"
android:orientation="vertical">
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="Title"
android:textColor="@color/black80"
android:textSize="@dimen/sp_16" />
android:id="@+id/tv_description"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="@dimen/dp_5"
android:text="Address"
android:textColor="@color/black40"
android:textSize="14sp" />
android:id="@+id/iv_check"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@mipmap/ic_map_ok" />
UI层
package com.qmd.app.module.mine.adapter;
import android.view.View;
import androidx.annotation.NonNull;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.qmd.app.R;
import com.qmd.app.module.mine.http.bean.SearchAddressInfo;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* @author: qy
* @description:
* @date: 2023/9/12 13:45
*/
public class PoiItemAdapterextends BaseQuickAdapter {
public PoiItemAdapter(List data) {
super(R.layout.item_map_poi, data);
}
@Override
protected void convert(@NonNull @NotNull BaseViewHolder viewHolder, SearchAddressInfo item) {
viewHolder.setText(R.id.tv_title, item.getTitle());
viewHolder.setText(R.id.tv_description, item.getDesc());
if (viewHolder.getAdapterPosition() ==0) {
viewHolder.getView(R.id.tv_description).setVisibility(View.GONE);
}else {
viewHolder.getView(R.id.tv_description).setVisibility(View.VISIBLE);
}
if (item.isChoose()) {
viewHolder.setVisible(R.id.iv_check, true);
viewHolder.setImageResource(R.id.iv_check, R.mipmap.ic_map_ok);
}else {
viewHolder.setVisible(R.id.iv_check, false);
}
}
}
2.
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="@+id/cl_chouti"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
android:id="@+id/titlebar"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_50"
app:layout_constraintTop_toTopOf="parent"
app:leftIcon="@null"
app:lineVisible="false"
app:title="地图选点" />
android:id="@+id/rtvSure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:background="@drawable/shape_round_5_blue"
android:paddingHorizontal="10dp"
android:paddingVertical="4dp"
android:text="确定"
android:textColor="@color/white"
android:textSize="@dimen/sp_16"
app:layout_constraintBottom_toBottomOf="@+id/titlebar"
app:layout_constraintEnd_toEndOf="parent" />
android:id="@+id/tvCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="@dimen/dp_10"
android:text="取消"
android:textColor="@color/black40"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@+id/rtvSure"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/rtvSure" />
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:visibility="gone"
app:cardCornerRadius="8dp"
app:cardElevation="4dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
app:layout_constraintTop_toBottomOf="@id/titlebar">
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:background="@null"
android:drawableStart="@drawable/ic_search_grey"
android:drawablePadding="8dp"
android:gravity="center_vertical"
android:hint="搜索关键词"
android:imeOptions="actionSearch"
android:maxLines="1"
android:padding="10dp"
android:singleLine="true"
android:textColor="#333333"
android:textSize="15dp" />
android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|end"
android:background="?selectableItemBackgroundBorderless"
android:padding="12dp"
android:paddingLeft="12dp"
android:src="@drawable/ic_navi_close"
android:visibility="invisible" />
android:id="@+id/iv_my_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:layout_marginLeft="@dimen/dp_10"
android:layout_marginBottom="@dimen/dp_290"
android:background="@drawable/shape_input_bg2"
android:padding="10dp"
android:src="@mipmap/icon_locartion" />
android:id="@+id/ll_bottom_sheet"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_alignParentBottom="true"
android:background="@drawable/map_sheet_bg"
android:orientation="vertical"
app:behavior_fitToContents="true"
app:behavior_hideable="false"
app:behavior_peekHeight="280dp"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
android:id="@+id/viewCloseHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:visibility="gone"
tools:layout_height="@dimen/dp_34">
android:id="@+id/ivCloseBottom"
android:layout_width="50dp"
android:layout_height="24dp"
android:layout_marginTop="@dimen/dp_10"
android:background="@drawable/shape_round_10_gray2"
android:src="@mipmap/drop_down_unselected_icon" />
android:layout_width="match_parent"
android:layout_height="@dimen/dp_40"
android:layout_marginTop="@dimen/dp_14"
android:paddingHorizontal="@dimen/dp_10">
android:id="@+id/llSearchPlace"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/shape_round_5_gray2"
android:gravity="center"
android:orientation="horizontal"
android:visibility="visible"
app:layout_constraintTop_toTopOf="parent">
android:layout_width="18dp"
android:layout_height="18dp"
android:src="@drawable/ic_search_grey" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="6dp"
android:text="搜索地点"
android:textColor="#999999"
android:textSize="13sp" />
android:id="@+id/llSearchInput"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center"
android:orientation="horizontal"
android:visibility="gone"
app:layout_constraintTop_toTopOf="parent">
android:id="@+id/etSearchContent"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/shape_round_5_gray2"
android:drawableStart="@drawable/ic_search_grey"
android:drawablePadding="6dp"
android:drawableTint="#999999"
android:gravity="center_vertical"
android:hint="搜索地点"
android:paddingHorizontal="10dp"
android:singleLine="true"
android:textSize="13sp" />
android:id="@+id/tvSearchCancel"
android:layout_width="40dp"
android:layout_height="match_parent"
android:layout_marginStart="6dp"
android:gravity="center_vertical|right"
android:text="取消"
android:textColor="#666666"
android:textSize="15sp" />
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="@dimen/dp_10">
android:id="@+id/rvPoiList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fafafa"
android:nestedScrollingEnabled="true"
android:overScrollMode="never"
android:scrollbars="none"
tools:listitem="@layout/item_map_poi" />
android:id="@+id/fl_loading_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
android:id="@+id/pb_progress"
style="@android:style/Widget.Holo.ProgressBar"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="@dimen/dp_20"
android:visibility="visible"
tools:ignore="MissingConstraints" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
package com.qmd.app.module.mine.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.cardview.widget.CardView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
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.animation.TranslateAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.hjq.bar.TitleBar;
import com.qmd.app.R;
import com.qmd.app.module.mine.adapter.PoiItemAdapter;
import com.qmd.app.module.mine.http.bean.SearchAddressInfo;
import com.qmd.core.aop.Log;
import com.qmd.core.app.BaseAppActivity;
import com.qmd.core.base.ABaseActivity;
import com.qmd.core.widget.decoration.SpacesItemDecoration;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import timber.log.Timber;
/**
* @author: qy
* @description:
* @date: 2023/9/12 11:46
*/
public class ChooseMap2Activityextends BaseAppActivityimplements View.OnClickListener, PoiSearch.OnPoiSearchListener, AMapLocationListener, LocationSource {
private static final StringINTENT_KEY_ADDRESS ="address";
private static final StringINTENT_KEY_ADDRESS_INFO ="addressInfo";
@Log
public static void start(ABaseActivity activity, String address, OnModifyListener listener) {
Intent intent =new Intent(activity, ChooseMap2Activity.class);
intent.putExtra(INTENT_KEY_ADDRESS, address);
activity.startActivityForResult(intent, (resultCode, data) -> {
if (listener ==null || data ==null) {
return;
}
if (resultCode ==RESULT_OK) {
SearchAddressInfo addressInfoBean = data.getParcelableExtra(INTENT_KEY_ADDRESS_INFO);
listener.onSucceed(addressInfoBean);
}else {
}
});
}
private CoordinatorLayoutclChouti;
private MapViewmapView;
private TitleBartitlebar;
private TextViewrtvSure;
private TextViewtvCancel;
private LinearLayoutllBottomSheet;
private ImageViewivCloseBottom;
private LinearLayoutllSearchPlace;
private LinearLayoutllSearchInput;
private AppCompatEditTextetSearchContent;
private TextViewtvSearchCancel;
private RecyclerViewrvPoiList;
private FrameLayoutflLoadingData;
private ProgressBarpbProgress;
private CardViewcardView;
private final int ZOOM =17;
private AMapaMap;
private BottomSheetBehaviorbehavior;
private int peekHeight;
private int sheetTotalHeight;
private MarkerscreenMarker =null;
private MyLocationStylemyLocationStyle;
private PoiItemAdapterpoiAdapter;
private ImageViewivMyLocation;
private TranslateAnimationanimation;
private ListmInfoList;
private StringcityName;
//是否手拖动地图
private boolean isHandDrag =true;
private int currentPage =0;
//开始位置
private LatLonPointstartPoint, lastPoint;
private KeyboardUtils.OnSoftInputChangedListenersoftInputChangedListener = height -> {
if (height >0) {
if (llSearchInput.getVisibility() == View.VISIBLE) {
if (behavior.getState() != BottomSheetBehavior.STATE_EXPANDED) {
etSearchContent.requestFocus();
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
}
}else {
if (llSearchInput.getVisibility() == View.VISIBLE) {
llSearchInput.requestFocus();
}
}
};
@Override
protected int getLayoutId() {
return R.layout.activity_choose_map2;
}
@Override
protected void initView() {
clChouti = (CoordinatorLayout) findViewById(R.id.cl_chouti);
mapView = (MapView) findViewById(R.id.mapView);
titlebar = (TitleBar) findViewById(R.id.titlebar);
rtvSure = (TextView) findViewById(R.id.rtvSure);
tvCancel = (TextView) findViewById(R.id.tvCancel);
llBottomSheet = (LinearLayout) findViewById(R.id.ll_bottom_sheet);
ivCloseBottom = (ImageView) findViewById(R.id.ivCloseBottom);
llSearchPlace = (LinearLayout) findViewById(R.id.llSearchPlace);
llSearchInput = (LinearLayout) findViewById(R.id.llSearchInput);
etSearchContent = (AppCompatEditText) findViewById(R.id.etSearchContent);
tvSearchCancel = (TextView) findViewById(R.id.tvSearchCancel);
rvPoiList = (RecyclerView) findViewById(R.id.rvPoiList);
flLoadingData = (FrameLayout) findViewById(R.id.fl_loading_data);
pbProgress = (ProgressBar) findViewById(R.id.pb_progress);
cardView = (CardView) findViewById(R.id.cardView);
ivMyLocation = (ImageView) findViewById(R.id.iv_my_location);
mapView.onCreate(savedInstanceState);
if (aMap ==null) {
aMap =mapView.getMap();
setUpMap();
}
setOnClickListener(R.id.ivCloseBottom, R.id.llSearchPlace,
R.id.tvSearchCancel, R.id.tvCancel, R.id.rtvSure, R.id.iv_my_location);
rvPoiList.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
isHandDrag =false;
mapView.setEnabled(false);
return false;
}else {
isHandDrag =true;
mapView.setEnabled(true);
return false;
}
}
});
}
@Override
protected void initData() {
initAdapter();
KeyboardUtils.registerSoftInputChangedListener(this, softInputChangedListener);
sheetTotalHeight = SizeUtils.dp2px(500);
peekHeight = SizeUtils.dp2px(280);
CoordinatorLayout.LayoutParams myLocationParams = (CoordinatorLayout.LayoutParams)ivMyLocation.getLayoutParams();
myLocationParams.setMargins(SizeUtils.dp2px(10), 0, 0, SizeUtils.dp2px(290));
ivMyLocation.setLayoutParams(myLocationParams);
behavior = BottomSheetBehavior.from(llBottomSheet);
behavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
boolean isExpand =false;
@Override
public void onStateChanged(@NonNull @NotNull View bottomSheet, int newState) {
switch (newState) {
case BottomSheetBehavior.STATE_COLLAPSED:
if (bottomSheet.getScrollY() !=0) {
bottomSheet.setScrollY(0);//列表滑动到顶端
}
break;
case BottomSheetBehavior.STATE_EXPANDED:
if (cardView.getTranslationY() !=0) {
cardView.setTranslationY(0);
}
break;
case BottomSheetBehavior.STATE_DRAGGING:
break;
}
}
@Override
public void onSlide(@NonNull @NotNull View bottomSheet, float slideOffset) {
float distance;
if (slideOffset >0) {//在peekHeight位置以上 滑动(向上、向下) slideOffset bottomSheet.getHeight() 是展开后的高度的比例
int height = bottomSheet.getHeight();
distance = height * slideOffset;
//地图跟随滑动,将我的位置移动到中心
aMap.moveCamera(CameraUpdateFactory.zoomTo(ZOOM));
aMap.moveCamera(CameraUpdateFactory.changeLatLng(getMyLocation()));
mapView.scrollTo(0, -(int) (distance /2f));
mapView.setTranslationY(-distance);
//搜索栏反向位移
float halfExpandedRatio =behavior.getHalfExpandedRatio();
float halfHeight = halfExpandedRatio * height;//中间状态的高度
if (distance > halfHeight) {
cardView.setTranslationY(-(distance - halfHeight));
cardView.setAlpha(1 - slideOffset + halfExpandedRatio);
}else {
cardView.setTranslationY(0);
cardView.setAlpha(1.0f);
}
isExpand =false;
}else {//在peekHeight位置以下 滑动(向上、向下) slideOffset 是PeekHeight的高度的比例
distance =behavior.getPeekHeight() * slideOffset;
isExpand =true;
}
}
});
llBottomSheet.post(() -> {
//设置bottomSheet的总高度
ViewGroup.LayoutParams params =llBottomSheet.getLayoutParams();
params.height =sheetTotalHeight;
llBottomSheet.setLayoutParams(params);
behavior.setFitToContents(true);//展开后开度填充Parent的高度
//setFitToContents 为false时,展开后距离顶部的位置(Parent会以PaddingTop填充)
behavior.setPeekHeight(peekHeight, true);
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
});
etSearchContent.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
if (!TextUtils.isEmpty(editable.toString())) {
doSearchQueryByKeyWord(editable.toString().trim());
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_my_location:
aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(startPoint.getLatitude(), startPoint.getLongitude()), 18, 30, 30)));
break;
case R.id.llSearchPlace:
llSearchPlace.setVisibility(View.GONE);
llSearchInput.setVisibility(View.VISIBLE);
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
postDelayed(new Runnable() {
@Override
public void run() {
KeyboardUtils.showSoftInput(etSearchContent);
}
}, 200);
break;
case R.id.tvSearchCancel:
flLoadingData.setVisibility(View.GONE);
KeyboardUtils.hideSoftInput(getWindow());
postDelayed(new Runnable() {
@Override
public void run() {
llSearchPlace.setVisibility(View.VISIBLE);
llSearchInput.setVisibility(View.GONE);
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}, 200);
break;
case R.id.tvCancel:
setResult(RESULT_CANCELED);
finish();
break;
case R.id.rtvSure:
if (lastPoint ==null) {
toast("请选择一个位置");
return;
}
getAddressInfo(false, null, lastPoint.getLatitude(), lastPoint.getLongitude());
break;
}
}
//默认位置
private LatLngdefaultLocation =new LatLng(37.870458, 112.549718);
public LatLnggetMyLocation() {
LatLng mPoint;
if (lastPoint !=null) {
mPoint =new LatLng(lastPoint.getLatitude(), lastPoint.getLongitude());
}else {
if (startPoint !=null) {
mPoint =new LatLng(startPoint.getLatitude(), startPoint.getLongitude());
}else {
mPoint =defaultLocation;
}
}
return mPoint;
}
/**
* 搜索结果适配器
**/
private void initAdapter() {
mInfoList =new ArrayList<>();
rvPoiList.setLayoutManager(new LinearLayoutManager(this));
rvPoiList.addItemDecoration(new SpacesItemDecoration(this, SpacesItemDecoration.VERTICAL)
.setNoShowDivider(0, 0)
.setDrawable(R.drawable.divider));
poiAdapter =new PoiItemAdapter(mInfoList);
rvPoiList.setAdapter(poiAdapter);
poiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
isHandDrag =false;
mapView.setEnabled(false);
lastPoint =new LatLonPoint(mInfoList.get(position).getLatitude(), mInfoList.get(position).getLongitude());
for (int i =0; i
mInfoList.get(i).setChoose(false);
}
mInfoList.get(position).setChoose(true);
poiAdapter.setNewData(mInfoList);
Timber.d("点击选中:" +lastPoint.getLatitude() +"--" +lastPoint.getLongitude());
LatLng latLng =new LatLng(mInfoList.get(position).getLatitude(), mInfoList.get(position).getLongitude());
aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 18, 30, 30)));
}
});
}
/**
* 设置一些amap的属性
*/
private void setUpMap() {
AMapLocationClient.updatePrivacyShow(this, true, true);
AMapLocationClient.updatePrivacyAgree(this, true);
// aMap.getUiSettings().setScaleControlsEnabled(true);// 标尺开关
// aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
aMap.getUiSettings().setZoomControlsEnabled(false);//缩放按钮
aMap.getUiSettings().setLogoBottomMargin(-100);
aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
/**
* 设置自定义定位蓝点
*/
myLocationStyle =new MyLocationStyle();
myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps_point));
myLocationStyle.anchor(0.5f, 0.5f);
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
myLocationStyle.showMyLocation(true);
myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
aMap.setMyLocationStyle(myLocationStyle);
aMap.moveCamera(CameraUpdateFactory.zoomTo(ZOOM));
aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
@Override
public void onMapLoaded() {
addMarkersToMap();
}
});
// 设置可视范围变化时的回调的接口方法
aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
}
@Override
public void onCameraChangeFinish(CameraPosition position) {
//屏幕中心的Marker跳动
startJumpAnimation();
if (!isHandDrag) {
isHandDrag =true;
mapView.setEnabled(true);
}else {
currentPage =0;
lastPoint =new LatLonPoint(position.target.latitude, position.target.longitude);
Timber.d("是否被响应:" +isHandDrag);
doSearchQueryByKeyWord("");
}
}
});
}
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation !=null && aMapLocation.getErrorCode() ==0) {
Timber.d("定位信息:" + aMapLocation.getAddress());
// mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
LatLng latLng =new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
startPoint =new LatLonPoint(latLng.latitude, latLng.longitude);
lastPoint =new LatLonPoint(latLng.latitude, latLng.longitude);
cityName = aMapLocation.getCity();
currentPage =0;
String s = GsonUtils.toJson(aMapLocation);
Timber.d("aMapLocation信息:" + s);
//addMarkersToMap();
//条目中第一个地址 也就是当前你所在的地址
aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 18, 30, 30)));
}else {
String errText ="定位失败," + aMapLocation.getErrorCode() +": " + aMapLocation.getErrorInfo();
Timber.d("AmapErr:" + errText);
}
}
private AMapLocationClientOptionmLocationOption;
//声明AMapLocationClient类对象
private AMapLocationClientmLocationClient =null;
/**
* 激活定位
*/
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
Timber.d("开始定位:");
if (mLocationClient ==null) {
try {
mLocationClient =new AMapLocationClient(this);
mLocationOption =new AMapLocationClientOption();
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//是指定位间隔
mLocationOption.setInterval(2000);
mLocationOption.setNeedAddress(true);
mLocationClient.setLocationOption(mLocationOption);
//设置定位回调监听
mLocationClient.setLocationListener(this::onLocationChanged);
mLocationClient.startLocation();
Timber.d("开始定位:");
}catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void deactivate() {
if (mLocationClient !=null) {
mLocationClient.stopLocation();
mLocationClient.onDestroy();
}
mLocationClient =null;
}
private PoiSearchpoiSearch;
private PoiSearch.QuerysearchQuery;
private void doSearchQueryByKeyWord(String keyWord) {
currentPage =0;
flLoadingData.setVisibility(View.VISIBLE);
searchQuery =new PoiSearch.Query(keyWord, "", cityName);
searchQuery.setPageSize(20);
searchQuery.setPageNum(currentPage);
searchQuery.setCityLimit(true);
if (lastPoint !=null) {
try {
poiSearch =new PoiSearch(this, searchQuery);
// 设置解析监听器
poiSearch.setOnPoiSearchListener(this);
poiSearch.setQuery(searchQuery);
poiSearch.setBound(new PoiSearch.SearchBound(lastPoint, 10000));
// 根据经纬度执行异步查询
Timber.d("是否查询:" +lastPoint.toString());
poiSearch.searchPOIAsyn();
}catch (AMapException e) {
e.printStackTrace();
}
}
}
/**
* 在地图上添加marker
*/
private void addMarkersToMap() {
addMarkerInScreenCenter();
}
/**
* 在屏幕中心添加一个Marker
*/
private void addMarkerInScreenCenter() {
// aMap.clear();
if (screenMarker !=null) {
return;
}
LatLng latLng =aMap.getCameraPosition().target;
Point screenPosition =aMap.getProjection().toScreenLocation(latLng);
screenMarker =aMap.addMarker(new MarkerOptions()
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_blue_pin)));
//设置Marker在屏幕上,不跟随地图移动
screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
}
/**
* 屏幕中心marker 跳动
*/
@SuppressLint("TimberArgCount")
public void startJumpAnimation() {
if (screenMarker !=null) {
//根据屏幕距离计算需要移动的目标点
LatLng latLng =screenMarker.getPosition();
Point point =aMap.getProjection().toScreenLocation(latLng);
point.y -= SizeUtils.dp2px(125);
LatLng target =aMap.getProjection().fromScreenLocation(point);
//使用TranslateAnimation,填写一个需要移动的目标点
animation =new TranslateAnimation(target);
// 模拟重加速度的interpolator
animation.setInterpolator((input) -> {
if (input <=0.5) {
return (float) (0.5f -2 * (0.5 - input) * (0.5 - input));
}else {
return (float) (0.5f - Math.sqrt((input -0.5f) * (1.5f - input)));
}
});
//整个移动所需要的时间
animation.setDuration(600);
//设置动画
screenMarker.setAnimation(animation);
//开始动画
screenMarker.startAnimation();
}else {
Timber.i("Marker" +"screenMarker is null");
}
}
/**
* 搜索结果
*/
private PoiResultpoiResult; // poi返回的结果
private ListpoiItems;// poi数据
@Override
public void onPoiSearched(PoiResult result, int rcode) {
flLoadingData.setVisibility(View.GONE);
if (rcode ==1000) {
if (result !=null && result.getQuery() !=null) {// 搜索poi的结果
if (result.getQuery().equals(searchQuery)) {// 是否是同一条
poiResult = result;
poiItems =poiResult.getPois();// 取得第一页的poiitem数据,页数从数字0开始
List suggestionCities =poiResult
.getSearchSuggestionCitys();// 当搜索不到poiitem数据时,会返回含有搜索关键字的城市信息
//搜索到数据
String json = GsonUtils.toJson(poiItems);
Timber.d("搜索结果:" + json);
if (poiItems !=null &&poiItems.size() >0) {
mInfoList.clear();
SearchAddressInfo addressInfo =null;
for (int i =0; i
PoiItem poiItem =poiItems.get(i);
String address = poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet();
addressInfo =new SearchAddressInfo(poiItem.getTitle(), address,
poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude(),
false);
mInfoList.add(addressInfo);
}
mInfoList.get(0).setChoose(true);
poiAdapter.setNewData(mInfoList);
}else if (suggestionCities !=null
&& suggestionCities.size() >0) {
showSuggestCity(suggestionCities);
}else {
toast("对不起,没有搜索到相关数据!");
}
}
}else {
toast("对不起,没有搜索到相关数据!");
}
}
}
/**
* poi没有搜索到数据,返回一些推荐城市的信息
*/
private void showSuggestCity(List cities) {
String infomation ="推荐城市\n";
for (int i =0; i < cities.size(); i++) {
infomation +="城市名称:" + cities.get(i).getCityName() +"城市区号:"
+ cities.get(i).getCityCode() +"城市编码:"
+ cities.get(i).getAdCode() +"\n";
}
toast(infomation);
}
@Override
public void onPoiItemSearched(PoiItem poiItem, int i) {
}
/**
* 1.地理编码(地址转坐标)
*/
private void getAddressInfo(boolean isAddressToLat, String addressName, double lat, double lng) {
//通过经纬度逆地理编码得到位置
GeocodeSearch geocodeSearch =null;
try {
geocodeSearch =new GeocodeSearch(getContext());
geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
if (i ==1000) {
if (regeocodeResult !=null && regeocodeResult.getRegeocodeAddress() !=null
&& regeocodeResult.getRegeocodeAddress().getFormatAddress() !=null) {
String formatAddress = regeocodeResult.getRegeocodeAddress().getFormatAddress();
String str = regeocodeResult.getRegeocodeAddress().getProvince() + regeocodeResult.getRegeocodeAddress().getCity();
Timber.d("地址1:" + formatAddress);
Timber.d("地址2:" + str);
SearchAddressInfo searchAddressInfo =new SearchAddressInfo();
searchAddressInfo.setLongitude(lng);
searchAddressInfo.setLatitude(lat);
searchAddressInfo.setAddressName(regeocodeResult.getRegeocodeAddress().getFormatAddress());
setResult(RESULT_OK, new Intent().putExtra(INTENT_KEY_ADDRESS_INFO, searchAddressInfo));
finish();
}
}
}
// 地理编码(地址转坐标)
@Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
if (i ==1000) {
double latitude = geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint().getLatitude();
double longitude = geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint().getLongitude();
}
}
});
if (isAddressToLat) {
// name表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode
GeocodeQuery query =new GeocodeQuery(addressName, cityName);
geocodeSearch.getFromLocationNameAsyn(query);
}else {
LatLonPoint latLng =new LatLonPoint(lat, lng);
//第一个参数表示一个Latlng,第二参数表示范围多少米,第三个参数表示是火系坐标系还是GPS原生坐标系
RegeocodeQuery query =new RegeocodeQuery(latLng, 200, GeocodeSearch.AMAP);
geocodeSearch.getFromLocationAsyn(query);
}
}catch (AMapException e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
if (mLocationClient !=null) {
mLocationClient.onDestroy();
}
if (animation !=null) {
animation.resetUpdateFlags();
animation.setAnimationListener(null);
}
if (screenMarker !=null) {
screenMarker.destroy();
}
mapView.onDestroy();
}
/**
* 修改监听监听
*/
public interface OnModifyListener {
/**
* 修改成功
*/
void onSucceed(SearchAddressInfo addressInfoBean);
}
}
package com.qmd.app.module.mine.http.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Fussen on 2016/11/1.
*
* 每个条目中的信息
*/
public class SearchAddressInfoimplements Parcelable {
public Stringtitle;
public Stringdesc;
public double latitude;
public double longitude;
public boolean isChoose;
private StringaddressName;
public SearchAddressInfo() {
}
public SearchAddressInfo(String title, String desc, double latitude, double longitude, boolean isChoose) {
this.title = title;
this.desc = desc;
this.latitude = latitude;
this.longitude = longitude;
this.isChoose = isChoose;
}
public StringgetAddressName() {
return addressName;
}
public void setAddressName(String addressName) {
this.addressName = addressName;
}
public StringgetTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public StringgetDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public boolean isChoose() {
return isChoose;
}
public void setChoose(boolean choose) {
isChoose = choose;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeString(this.desc);
dest.writeDouble(this.latitude);
dest.writeDouble(this.longitude);
dest.writeByte(this.isChoose ? (byte)1 : (byte)0);
dest.writeString(this.addressName);
}
public void readFromParcel(Parcel source) {
this.title = source.readString();
this.desc = source.readString();
this.latitude = source.readDouble();
this.longitude = source.readDouble();
this.isChoose = source.readByte() !=0;
this.addressName = source.readString();
}
protected SearchAddressInfo(Parcel in) {
this.title = in.readString();
this.desc = in.readString();
this.latitude = in.readDouble();
this.longitude = in.readDouble();
this.isChoose = in.readByte() !=0;
this.addressName = in.readString();
}
public static final CreatorCREATOR =new Creator() {
@Override
public SearchAddressInfocreateFromParcel(Parcel source) {
return new SearchAddressInfo(source);
}
@Override
public SearchAddressInfo[]newArray(int size) {
return new SearchAddressInfo[size];
}
};
}