Android实现高德地图SDK搜索及结果列表展示功能

在这里插入图片描述

1:首先去高德开放平台去进行一些配置高德开放平台官网
2:再去Android studio你的项目中进行配置Android studio配置流程

3:清单文件中加入权限及官网上获取的key值
4:可以写代码咯
MainActivity布局代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<!--    <include layout="@layout/comment_title"/>-->

    <com.amap.api.maps.MapView
        android:id="@+id/baidu_map"
        android:layout_below="@+id/tv_toplan"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:clickable="true"
        android:background="#fff"
        />
    <TextView
        android:id="@+id/tvBaiduJuli"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="15sp"
        android:textColor="@color/history_text"
        android:layout_below="@+id/tv_toplan"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="36dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="52dp">
            <TextView
                android:id="@+id/seach_cancel"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="取消"
                android:layout_marginRight="10dp"
                android:textColor="@color/buyvips"
                android:background="@drawable/search_shape"
                android:gravity="center_vertical"
                android:textSize="14sp"/>
            <TextView
                android:id="@+id/seach_sure"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="搜索"
                android:layout_marginLeft="10dp"
                android:layout_alignParentRight="true"
                android:textColor="@color/buyvips"
                android:background="@drawable/search_shape"
                android:gravity="center_vertical"
                android:textSize="14sp"/>

            <AutoCompleteTextView
                android:id="@+id/seach_name"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:drawableLeft="@drawable/seachgray"
                android:background="@drawable/search_shape"
                android:completionThreshold="1"
                android:drawablePadding="5dp"
                android:dropDownVerticalOffset="1.0dip"
                android:focusable="true"
                android:gravity="center_vertical"
                android:hint="请输入城市名称"
                android:layout_toLeftOf="@id/seach_sure"
                android:layout_toRightOf="@id/seach_cancel"
                android:imeOptions="actionSearch"
                android:inputType="text|textAutoComplete"
                android:maxLength="20"
                android:paddingLeft="14dp"
                android:singleLine="true"
                android:textColor="#979EA9"
                android:textColorHint="#979EA9"
                android:textSize="14.0sp" />

    </RelativeLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recy_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/baidu_map"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"/>

</RelativeLayout>

主要Mainactvity中代码,全给你们了,不要在乎名字,刚开始本来打算用百度地图,结果发现很多bug就改用高德安全性高一点哈哈哈

public class BaiduMapActivity extends Activity implements AMapLocationListener, LocationSource, PoiSearch.OnPoiSearchListener {
    
    
    @BindView(R.id.seach_name)
    AutoCompleteTextView seachName;
    @BindView(R.id.seach_cancel)
    TextView seachCancel;
    @BindView(R.id.recy_name)
    RecyclerView recyName;
    @BindView(R.id.seach_sure)
    TextView seachSure;
    private AMap mAmap;
    /**
     * 地图对象
     */
    private AMapLocationClient mlocationClient;
    private MapView mRouteMapView;
    private Marker mStartMarker;
    private Marker mEndMarker;


    /**
     * 途径点坐标集合
     */
    /**
     * 终点坐标集合[建议就一个终点]
     */
    private AMapLocationClientOption mLocationOption;
    private OnLocationChangedListener mListener;
    private boolean useThemestatusBarColor = false;
    private Double startLat, startLon;
    private TextView tvJuLi;
    private LogineDialog progDialog = null;
    private MapAdapter mMapAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actctivity_baidumap);
        ButterKnife.bind(this);
        setStatusBar();
        initData();
        mRouteMapView = findViewById(R.id.baidu_map);
        tvJuLi = findViewById(R.id.tvBaiduJuli);
        mRouteMapView.onCreate(savedInstanceState);
        mAmap = mRouteMapView.getMap();
        // 初始化Marker添加到地图
        mStartMarker = mAmap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.start))));
        mEndMarker = mAmap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.end))));
        init();
        mMapAdapter = new MapAdapter(BaiduMapActivity.this);
        mMapAdapter.setOnItemClickListener(new MapAdapter.OnItemClickListener() {
    
    
            @Override
            public void onItemClick(String name, String content) {
    
    
                finish();
                EventBus.getDefault().post(new TwoMessageEvent(name,content));
            }
        });

    }

    private void initData() {
    
    
        //软键盘回车变搜索按钮
            seachName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    
    
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    
    
                    if (actionId == EditorInfo.IME_ACTION_SEARCH){
    
    
                        String input=seachName.getText().toString();
                        if(!TextUtils.isEmpty(input)){
    
    
                            PoiSearch.Query query = new PoiSearch.Query(input, "", "");
                            query.setPageSize(30);
                            query.setPageNum(0);
                            PoiSearch poiSearch = new PoiSearch(BaiduMapActivity.this, query);
                            poiSearch.setOnPoiSearchListener(BaiduMapActivity.this);
                            poiSearch.searchPOIAsyn();
                            //关闭软键盘
                            closeKeybord(BaiduMapActivity.this);

                        }
                        return true;
                    }
                    return false;
                }
            });
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
    
    
        super.onResume();
        mRouteMapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
    
    
        super.onPause();
        mRouteMapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    
    
        super.onSaveInstanceState(outState);
        mRouteMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        // mRouteMapView.onDestroy();
        if (null != mlocationClient) {
    
    
            mlocationClient.onDestroy();
        }
        EventBus.getDefault().unregister(this);
    }


    /**
     * 初始化
     */
    private void init() {
    
    
        if (mAmap == null) {
    
    
            mAmap = mRouteMapView.getMap();
            setUpMap();
        } else {
    
    
            setUpMap();
        }

    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
    
    
        mAmap.getUiSettings().setLogoBottomMargin(-50);
        mAmap.getUiSettings().setZoomControlsEnabled(false);
        mAmap.setLocationSource(this);// 设置定位监听
        mAmap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        mAmap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
        mAmap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
    
    
        mListener = listener;
        if (mlocationClient == null) {
    
    
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setOnceLocation(true);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
            // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后,在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
    
    
        mListener = null;
        if (mlocationClient != null) {
    
    
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
    
    
        if (mListener != null && amapLocation != null) {
    
    
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {
    
    
                mListener.onLocationChanged(amapLocation);
                startLat = amapLocation.getLatitude();
                startLon = amapLocation.getLongitude();
                mStartMarker.setPosition(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude()));
            } else {
    
    
                if (progDialog != null) {
    
    
                    progDialog.dismiss();
                }
            }
        }
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
    
    

    }

    protected void setStatusBar() {
    
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    
    
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            if (useThemestatusBarColor) {
    
    
                getWindow().setStatusBarColor(getResources().getColor(R.color.articleTitle));
            } else {
    
    
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    
    
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }
    @OnClick({
    
    R.id.seach_sure, R.id.seach_cancel})
    public void onViewClicked(View view) {
    
    
        switch (view.getId()) {
    
    
            case R.id.seach_sure://确认
                String keyword = seachName.getText().toString().trim();
                PoiSearch.Query query = new PoiSearch.Query(keyword, "", "");
                query.setPageSize(30);
                query.setPageNum(0);
                PoiSearch poiSearch = new PoiSearch(BaiduMapActivity.this, query);
                poiSearch.setOnPoiSearchListener(this);
                poiSearch.searchPOIAsyn();
                closeKeybord(BaiduMapActivity.this);

                break;
            case R.id.seach_cancel://返回
                finish();
                break;
        }
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
    
    
        if (i == 1000) {
    
    
            ArrayList<AddressBean> data = new ArrayList<AddressBean>();
            ArrayList<PoiItem> items = poiResult.getPois();
            for(PoiItem item : items){
    
    
                //获取经纬度对象
                LatLonPoint llp = item.getLatLonPoint();
                double lon = llp.getLongitude();
                double lat = llp.getLatitude();
                //获取标题
                String title = item.getTitle();
                //获取内容
                String text = item.getSnippet();
                data.add(new AddressBean(lon, lat, title, text));
            }
            recyName.setLayoutManager(new GridLayoutManager(this, 1, GridLayoutManager.VERTICAL, false));
            recyName.setAdapter(mMapAdapter);
            mMapAdapter.setData(data);
            mMapAdapter.notifyDataSetChanged();

        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
    
    

    }

    /**
     * 自动关闭软键盘
     * @param activity
     */
    public static void closeKeybord(Activity activity) {
    
    
        InputMethodManager imm =  (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm != null) {
    
    
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }
}

存储数据的bean类AddressBean

public class AddressBean {
    
    
    private double longitude;//经度
    private double latitude;//纬度
    private String title;//信息标题
    private String text;//信息内容
    public AddressBean(double lon, double lat, String title, String text){
    
    
        this.longitude = lon;
        this.latitude = lat;
        this.title = title;
        this.text = text;
    }
    public double getLongitude() {
    
    
        return longitude;
    }

    public double getLatitude() {
    
    
        return latitude;
    }
    public String getTitle() {
    
    
        return title;
    }
    public String getText(){
    
    
        return text;
    }
}

列表展示的适配器

public class MapAdapter extends RecyclerView.Adapter<MapAdapter.ViewHolder> {
    
    
    private Activity mActivity;
    private List<AddressBean> list;

    public MapAdapter(Activity activity) {
    
    
        this.mActivity = activity;
    }



    protected OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
    
    
        void onItemClick(String name,String content);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
    
    
        this.mItemClickListener = listener;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    
    
        ViewHolder holder = new ViewHolder(LayoutInflater.from(mActivity).inflate(R.layout.map_item, viewGroup, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
    
    
        if (list.size() !=0){
    
    
            viewHolder.mMapname.setText(list.get(i).getTitle());
            viewHolder.mMapcontent.setText(list.get(i).getText());
        }
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                if (mItemClickListener !=null){
    
    
                    mItemClickListener.onItemClick(list.get(i).getTitle(),list.get(i).getText());
                }
            }
        });
    }
    /**
     * 设置数据集
     * @param data
     */
    public void setData(List<AddressBean> data){
    
    
        this.list = data;
    }
    @Override
    public int getItemCount() {
    
    
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
    
    

        private final TextView mMapname,mMapcontent;
        private final RelativeLayout relay;

        public ViewHolder(@NonNull View itemView) {
    
    
            super(itemView);
            relay = itemView.findViewById(R.id.relay);
            mMapname = itemView.findViewById(R.id.map_title);
            mMapcontent = itemView.findViewById(R.id.map_content);
        }
    }
}

列表布局map_item

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relay"
    android:gravity="center_vertical"
    android:layout_marginTop="12dp">
    <ImageView
        android:id="@+id/map_dw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/start"
        />
    <TextView
        android:id="@+id/map_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="12dp"
        android:text="11111111111"
        android:lines="1"
        android:ellipsize="end"
        android:layout_toRightOf="@id/map_dw"
        android:textSize="14sp"/>
    <TextView
        android:id="@+id/map_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/map_dw"
        android:text="22222222222222"
        android:lines="1"
        android:ellipsize="end"
        android:layout_marginLeft="12dp"
        android:layout_below="@id/map_title"
        android:textSize="14sp"/>

</RelativeLayout>

应该大概也许可能就这些东西了,代码太多有点分不清,找不到的再问我嘻嘻

猜你喜欢

转载自blog.csdn.net/weixin_43117800/article/details/106070442
今日推荐