1. 程式人生 > >百度地圖開發(八)輸入框搜尋根據關鍵字檢索出現列表

百度地圖開發(八)輸入框搜尋根據關鍵字檢索出現列表

 看圖

 效果就是輸入自動提示熱詞,點選熱詞賦值給輸入框

介面卡程式碼

package com.example.administrator.baidumap1;

/*
 * @Comment :
 * @Created :2018/10/26 14:11
 * @Name : YJ
 */

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by weihao on 2018/5/28.
 * 繼承BaseAdapter,實現Filterable
 */

public class AutoEditTextAdapter extends BaseAdapter implements Filterable {
    private ArrayFilter mFilter;
    private List<String> mList;
    private List<String> mList2;
    private Context context;
    private OnItemClickListener mOnItemClickListener;
    private ArrayList<String> mUnfilteredData;

    public interface OnItemClickListener{
        void onClick( int position);
        void onLongClick( int position);
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener ){
        this. mOnItemClickListener=onItemClickListener;
    }

    public AutoEditTextAdapter(List<String> mList, List<String> mList2, Context context) {
        this.mList = mList;
        this.context = context;
        this.mList2 = mList2;
    }

    @Override
    public int getCount() {

        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view;
        ViewHolder holder;
        if (convertView == null) {
            view = View.inflate(context, R.layout.item, null);

            holder = new ViewHolder();
            holder.text1 = (TextView) view.findViewById(R.id.name);
            holder.text2=view.findViewById(R.id.address);
            holder.dianji=view.findViewById(R.id.dianji);

            view.setTag(holder);
        } else {
            view = convertView;
            holder = (ViewHolder) view.getTag();
        }
//item的點選事件
        if( mOnItemClickListener!= null){
            holder.dianji.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.onClick(position);
                }
            });
            holder.dianji.setOnLongClickListener( new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    mOnItemClickListener.onLongClick(position);
                    return false;
                }
            });
        }
        String pc = mList.get(position);
        String pc2=mList2.get(position);

        holder.text1.setText(pc);
        holder.text2.setText(pc2);


        return view;
    }

    static class ViewHolder {
        public TextView text1;
        public TextView text2;
        public LinearLayout dianji;

    }

    @Override
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new ArrayFilter();
        }
        return mFilter;
    }

    private class ArrayFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();

            if (mUnfilteredData == null) {
                mUnfilteredData = new ArrayList<String>(mList);
            }

            if (prefix == null || prefix.length() == 0) {
                ArrayList<String> list = mUnfilteredData;
                results.values = list;
                results.count = list.size();
            } else {
                String prefixString = prefix.toString().toLowerCase();

                ArrayList<String> unfilteredValues = mUnfilteredData;
                int count = unfilteredValues.size();

                ArrayList<String> newValues = new ArrayList<String>(count);

                for (int i = 0; i < count; i++) {
                    String pc = unfilteredValues.get(i);
                    if (pc != null) {

                        if (pc != null && pc.startsWith(prefixString)) {

                            newValues.add(pc);
                        } else if (pc != null && pc.startsWith(prefixString)) {

                            newValues.add(pc);
                        }
                    }
                }

                results.values = newValues;
                results.count = newValues.size();
            }

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {

            mList = (List<String>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }

    }
}

item佈局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:id="@+id/dianji"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:gravity="center_vertical"
        android:padding="10dp"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="wrap_content"
            android:src="@mipmap/icon_dingwei"
            android:layout_height="wrap_content" />
        <LinearLayout
            android:layout_width="match_parent"
            android:paddingLeft="10dp"
            android:orientation="vertical"
            android:layout_height="wrap_content">
            <TextView
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:text="name"
                android:textSize="15sp"
                android:textColor="#000"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/address"
                android:layout_width="match_parent"
                android:text="address"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </LinearLayout>


    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f2f2f2"/>

</LinearLayout>

MainActivity佈局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <AutoCompleteTextView
        android:id="@+id/editaddress"
        android:layout_width="match_parent"
        android:background="@null"
        android:completionThreshold="2"
        android:hint="請輸入地址"
        android:padding="15dp"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="220dp">
        <com.baidu.mapapi.map.MapView
            android:id="@+id/mapview"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </com.baidu.mapapi.map.MapView>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_centerInParent="true"
            android:paddingBottom="20dp"
            android:src="@mipmap/dingwei2" />

        <ImageView
            android:id="@+id/sa_location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_margin="10dp"
            android:src="@mipmap/icon_location" />

    </RelativeLayout>

    <TextView
        android:id="@+id/jieguo"
        android:layout_width="match_parent"
        android:text="輸入位置附近的位置"
        android:padding="15dp"
        android:layout_height="match_parent" />

</LinearLayout>

MainActivity裡面的程式碼:

package com.example.administrator.baidumap1;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

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.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Text;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.linsh.utilseverywhere.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private ImageView mSaLocation;
    private LocationClient mLocationClient;
    private LatLng latLng;
    private boolean isFirstLoc = true;//是否是首次定位
    public BDLocationListener myListener = new MyLocationListener();
    private MyLocationData locData;
    private double mLatitude;
    private double mLongitude;
    private TextView mJieguo;
    private AutoCompleteTextView mEditAddress;
    private List<String> stringlist = new ArrayList<>();
    private List<String> stringlist2 = new ArrayList<>();
    private SuggestionSearch mSuggestionSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setInit();
        initMap();
    }

    public void setInit() {
        mMapView = findViewById(R.id.mapview);
        mBaiduMap = mMapView.getMap();
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(listener);
        mMapView.showZoomControls(false);
        mSaLocation = findViewById(R.id.sa_location);
        mSaLocation.setOnClickListener(this);
        mEditAddress = findViewById(R.id.editaddress);
        mJieguo = findViewById(R.id.jieguo);
    }

    /**
     * 監聽輸入框的輸入
     */
    public void setEdit(final String city) {
        //點選就自動提示
        mEditAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditAddress.showDropDown();
            }
        });

        mEditAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                        .keyword(mEditAddress.getText().toString())
                        .city(city));
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    OnGetSuggestionResultListener listener = new OnGetSuggestionResultListener() {
        public void onGetSuggestionResult(SuggestionResult res) {
            if (res == null || res.getAllSuggestions() == null) {//未找到相關結果
                return;
            } else {//獲取線上建議檢索結果
                List<SuggestionResult.SuggestionInfo> resl = res.getAllSuggestions();
                stringlist.clear();
                stringlist2.clear();
                for (int i = 0; i < resl.size(); i++) {
                    stringlist.add(resl.get(i).key);
                    stringlist2.add(resl.get(i).city+resl.get(i).district+resl.get(i).key);
                    latLng = resl.get(i).pt;
                }
                mJieguo.setText("" + resl);
                AutoEditTextAdapter adapter = new AutoEditTextAdapter(stringlist,stringlist2, MainActivity.this);
                mEditAddress.setAdapter(adapter);
                adapter.setOnItemClickListener(new AutoEditTextAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        Toast.makeText(MainActivity.this,""+position,Toast.LENGTH_SHORT).show();
                        mEditAddress.setText(stringlist.get(position));
                        mEditAddress.dismissDropDown();
                    }

                    @Override
                    public void onLongClick(int position) {

                    }
                });
            }
        }
    };

    /**
     * 定位
     */
    private void initMap() {
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);//預設顯示普通地圖
        mBaiduMap.setMyLocationEnabled(true);// 開啟定點陣圖層
        mLocationClient = new LocationClient(getApplicationContext());     //宣告LocationClient類
        initLocation();//配置定位SDK引數
        mLocationClient.registerLocationListener(myListener);    //註冊監聽函式
        mLocationClient.start();//開啟定位
        mLocationClient.requestLocation();//圖片點選事件,回到定位點
    }

    /**
     * 配置定位SDK引數
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");//可選,coorType - 取值有3個: 返回國測局經緯度座標系:gcj02 返回百度墨卡託座標系 :bd09 返回百度經緯度座標系 :bd09ll
        Log.e("獲取地址資訊設定", option.getAddrType());//獲取地址資訊設定
        option.setIsNeedAddress(true);//可選,設定是否需要地址資訊,預設不需要
        option.setOpenGps(true); // 是否開啟gps進行定位
        option.setLocationNotify(true);//可選,預設false,設定是否當GPS有效時按照1S/1次頻率輸出GPS結果
        option.setScanSpan(1000);//可選,設定的掃描間隔,單位是毫秒,設定發起定位請求的間隔需要大於等於1000ms才是有效的
        Log.e("獲取設定的Prod欄位值", option.getProdName());
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可選,預設高精度,設定定位模式,高精度,低功耗,僅裝置
        option.setNeedDeviceDirect(true);//在網路定位時,是否需要裝置方向- true:需要 ; false:不需要。預設為false
        option.SetIgnoreCacheException(false);//可選,預設false,設定是否收集CRASH資訊,預設收集
        option.setIgnoreKillProcess(false);//可選,預設true,定位SDK內部是一個SERVICE,並放到了獨立程序,設定是否在stop的時候殺死這個程序,預設不殺死
        option.setIsNeedLocationDescribe(true);//可選,預設false,設定是否需要位置語義化結果,可以在BDLocation
        // .getLocationDescribe裡得到,結果類似於“在北京天安門附近”
        option.setIsNeedLocationPoiList(true);//可選,預設false,設定是否需要POI結果,可以在BDLocation.getPoiList裡得到
        option.setEnableSimulateGps(false);//可選,預設false,設定是否需要過濾GPS模擬結果,預設需要
        mLocationClient.setLocOption(option);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sa_location:
                //把定位點再次顯現出來
                MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latLng);
                mBaiduMap.animateMapStatus(mapStatusUpdate);
                break;
        }
    }

    //實現BDLocationListener介面,BDLocationListener為結果監聽介面,非同步獲取定位結果
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(final BDLocation location) {
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            // 構造定位資料
            mLatitude = location.getLatitude();
            mLongitude = location.getLongitude();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .direction(100)// 此處設定開發者獲取到的方向資訊,順時針0-360
                    .latitude(mLatitude)
                    .longitude(mLongitude).build();
            mBaiduMap.setMyLocationData(locData);// 設定定位資料

            setEdit(location.getCity());

            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(latLng).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位結果
                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 網路定位結果
                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 離線定位結果
                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeServerError) {//伺服器錯誤
                    Toast.makeText(MainActivity.this, "伺服器錯誤,請檢查", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {//網路錯誤
                    Toast.makeText(MainActivity.this, "網路錯誤,請檢查", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {//手機模式錯誤
                    Toast.makeText(MainActivity.this, "手機模式錯誤,請檢查是否飛行", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
}

下載地址:https://download.csdn.net/download/lanrenxiaowen/10746774