集成高德地图定位功能 https://mp.csdn.net/postedit/87602009
1.在第一次定位结束要搜索周边
/**
* 周边搜索
*/
private void poiSearch(double longitude, double latitude, int distances) {
LatLonPoint point=new LatLonPoint(latitude,longitude);
GeocodeSearch geocodeSearch=new GeocodeSearch(getActivity());
RegeocodeQuery regeocodeQuery=new RegeocodeQuery(point,distances,geocodeSearch.AMAP);
geocodeSearch.getFromLocationAsyn(regeocodeQuery);
geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
Logger.d(rCode);
if (1000==rCode){
RegeocodeAddress address=regeocodeResult.getRegeocodeAddress();
StringBuffer stringBuffer=new StringBuffer();
String area = address.getProvince();//省或直辖市
cityName = address.getCity();//地级市或直辖市
String subLoc = address.getDistrict();//区或县或县级市
List pois = address.getPois();//获取周围兴趣点
Logger.d("地区="+area);
poiAdapter.refreshDatas(pois);
cameraMarkers(regeocodeResult.getRegeocodeQuery().getPoint().getLatitude(),regeocodeResult.getRegeocodeQuery().getPoint().getLongitude());
}
}
@Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {
Logger.d(rCode);
Logger.d(geocodeResult.getGeocodeAddressList());
Logger.d(geocodeResult.getGeocodeQuery());
}
});
}
2.监听手指滑动地图,当滑动地图之后,重新搜索周边
aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
poiSearch(cameraPosition.target.longitude,cameraPosition.target.latitude,2000);
}
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
}
});
3.关键字搜索
private void doSearchQuery(String keyWord) {
PoiSearch.Query query = new PoiSearch.Query(keyWord, "", cityName);
query.setPageSize(30);
query.setPageNum(0);
PoiSearch poiSearch = new PoiSearch(_mActivity, query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.searchPOIAsyn();
}
@Override
public void onPoiSearched(PoiResult poiResult, int rCode) {
if (rCode== AMapException.CODE_AMAP_SUCCESS){
ArrayList pois = poiResult.getPois();
poiAdapter.refreshDatas(pois);
cameraMarkers(poiResult.getQuery().getLocation().getLatitude(),poiResult.getQuery().getLocation().getLongitude());
}
}
4.完整代码
package com.dejun.map.fragment;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
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.CameraUpdate;
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.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.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
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.dejun.commonsdk.base.BaseFragment;
import com.dejun.commonsdk.base.mvp.BasePresenter;
import com.dejun.commonsdk.wight.CustomSearchView;
import com.dejun.map.R;
import com.dejun.map.adapter.PoiAdapter;
import com.orhanobut.logger.Logger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Author:DoctorWei
* Time:2019/2/13 14:24
* Description:
* email:[email protected]
*/
public class LocationFragment extends BaseFragment implements LocationSource, AMapLocationListener,PoiSearch.OnPoiSearchListener {
private MapView mMapView;
AMap aMap;
OnLocationChangedListener mListener;
AMapLocationClient mlocationClient;
AMapLocationClientOption mLocationOption;
Marker marker;
RecyclerView mRvLocationList;
PoiAdapter poiAdapter;
List poiItems=new ArrayList<>();
private View view;
private CustomSearchView mCsvLocationSearch;
public static LocationFragment newInstance() {
return new LocationFragment();
}
@Override
protected BasePresenter createPresenter() {
return null;
}
@Override
protected int getLayoutId() {
return R.layout.fragment_location_layout;
}
@Override
protected void initView(View view) {
//获取地图控件引用
mMapView = (MapView) view.findViewById(R.id.csv_location_map);
mRvLocationList = (RecyclerView) view.findViewById(R.id.rv_location_list);
mRvLocationList.setLayoutManager(new LinearLayoutManager(_mActivity,LinearLayoutManager.VERTICAL,false));
poiAdapter=new PoiAdapter(poiItems,_mActivity,R.layout.poi_item_layout);
mRvLocationList.setAdapter(poiAdapter);
mCsvLocationSearch = (CustomSearchView) view.findViewById(R.id.csv_location_search);
mCsvLocationSearch.setSearchViewSearchListener(new CustomSearchView.SearchViewSearchListener() {
@Override
public void search(String content) {
if (!TextUtils.isEmpty(content)){
doSearchQuery(content);
}
}
});
}
private void doSearchQuery(String keyWord) {
PoiSearch.Query query = new PoiSearch.Query(keyWord, "", cityName);
query.setPageSize(30);
query.setPageNum(0);
PoiSearch poiSearch = new PoiSearch(_mActivity, query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.searchPOIAsyn();
}
@Override
protected void initData(Bundle savedInstanceState) {
//在activity执行onCreate时执行mMapView.onCreate(savedInstanceState),创建地图
mMapView.onCreate(savedInstanceState);
//初始化地图控制器对象
if (aMap == null) {
aMap = mMapView.getMap();
}
MyLocationStyle locationStyle = new MyLocationStyle();
locationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
locationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
aMap.setMyLocationStyle( locationStyle);
// 设置定位监听
aMap.setLocationSource(this);
// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
aMap.setMyLocationEnabled(true);
// 设置定位的类型为定位模式,有定位、跟随或地图根据面向方向旋转几种
aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
//监听地图发生变化之后
aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
poiSearch(cameraPosition.target.longitude,cameraPosition.target.latitude,2000);
}
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
}
});
UiSettings uiSettings = aMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
uiSettings.setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
}
@Override
public void onDestroyView() {
super.onDestroyView();
//在activity执行onDestroy时执行mMapView.onDestroy(),销毁地图
mMapView.onDestroy();
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView.onPause (),暂停地图的绘制
mMapView.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),保存地图当前的状态
mMapView.onSaveInstanceState(outState);
}
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
fixLocation(onLocationChangedListener);
}
private void fixLocation(OnLocationChangedListener onLocationChangedListener) {
mListener = onLocationChangedListener;
if (mlocationClient == null) {
//初始化定位
mlocationClient = new AMapLocationClient(_mActivity);
//初始化定位参数
mLocationOption = new AMapLocationClientOption();
//设置定位回调监听
mlocationClient.setLocationListener(this);
mLocationOption.setOnceLocation(true); //只定位一次
//设置为高精度定位模式
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位参数
mlocationClient.setLocationOption(mLocationOption);
mlocationClient.startLocation();//启动定位
}
}
@Override
public void deactivate() {
mListener = null;
if (mlocationClient !=null){
mlocationClient.stopLocation();
mlocationClient.onDestroy();
}
mlocationClient = null;
mLocationOption = null;
}
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation.getErrorCode() == 0) {
//定位成功回调信息,设置相关消息
aMapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见定位类型表
double longitude = aMapLocation.getLongitude();//获取经度
double latitude = aMapLocation.getLatitude();//获取纬度
aMapLocation.getAccuracy();//获取精度信息
String adCode = aMapLocation.getAdCode();
String cityCode = aMapLocation.getCityCode();
cityName = aMapLocation.getCity();
String address = aMapLocation.getAddress();
String aoiName = aMapLocation.getAoiName();
String poiName = aMapLocation.getPoiName();
String coordType = aMapLocation.getCoordType();
String country = aMapLocation.getCountry();
Logger.d("adCode=" + adCode + " cityName=" + cityName + " address=" + address + " aoiName=" + aoiName + " poiName=" + poiName + " coordType=" + coordType + " country=" + country);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(aMapLocation.getTime());
df.format(date);//定位时间
mListener.onLocationChanged(aMapLocation);
//获取定位信息进行周边搜索
poiSearch(longitude ,latitude,2000);
cameraMove(latitude,longitude);
} else {
//显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。
Logger.e("location Error, ErrCode:"
+ aMapLocation.getErrorCode() + ", errInfo:"
+ aMapLocation.getErrorInfo());
}
}
/**
* 移动地图
* @param lat
* @param lng
*/
private void cameraMove(double lat,double lng) {
LatLng latlng = new LatLng(lat, lng);
CameraUpdate camera = CameraUpdateFactory.newCameraPosition(new CameraPosition(latlng, 18, 0, 0));
aMap.moveCamera(camera);
}
private void cameraMarkers(double lat,double lng) {
if (marker!=null) {
marker.remove();
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(lat, lng));
markerOptions.title("当前位置");
markerOptions.visible(true);
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.arrow_left_back));
markerOptions.icon(bitmapDescriptor);
marker = aMap.addMarker(markerOptions);
}
private String cityName;
/**
* 周边搜索
*/
private void poiSearch(double longitude, double latitude, int distances) {
LatLonPoint point=new LatLonPoint(latitude,longitude);
GeocodeSearch geocodeSearch=new GeocodeSearch(getActivity());
RegeocodeQuery regeocodeQuery=new RegeocodeQuery(point,distances,geocodeSearch.AMAP);
geocodeSearch.getFromLocationAsyn(regeocodeQuery);
geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
Logger.d(rCode);
if (1000==rCode){
RegeocodeAddress address=regeocodeResult.getRegeocodeAddress();
StringBuffer stringBuffer=new StringBuffer();
String area = address.getProvince();//省或直辖市
cityName = address.getCity();//地级市或直辖市
String subLoc = address.getDistrict();//区或县或县级市
List pois = address.getPois();//获取周围兴趣点
Logger.d("地区="+area);
poiAdapter.refreshDatas(pois);
cameraMarkers(regeocodeResult.getRegeocodeQuery().getPoint().getLatitude(),regeocodeResult.getRegeocodeQuery().getPoint().getLongitude());
}
}
@Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {
Logger.d(rCode);
Logger.d(geocodeResult.getGeocodeAddressList());
Logger.d(geocodeResult.getGeocodeQuery());
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
if (null != mlocationClient) {
mlocationClient.onDestroy();
}
}
@Override
public void onPoiSearched(PoiResult poiResult, int rCode) {
if (rCode== AMapException.CODE_AMAP_SUCCESS){
ArrayList pois = poiResult.getPois();
poiAdapter.refreshDatas(pois);
cameraMarkers(poiResult.getQuery().getLocation().getLatitude(),poiResult.getQuery().getLocation().getLongitude());
}
}
@Override
public void onPoiItemSearched(PoiItem poiItem, int i) {
}
//
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// view = View.inflate(getActivity(), R.layout.fragment_location_layout, null);
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// // TODO:OnCreateView Method has been created, run FindViewById again to generate code
// initView(view);
// return view;
// }
}