使用高德地圖仿最新版微信發送位置實現,相似度高達99.99%!!!

背景

其實程序猿要開發一個demo的背景,都!一!樣!
說什麼爲了社會進步,爲了挑戰自我,都!是!瞎!扯!蛋!
無非就是一個背景,產品經理要求實現該功能!!!

生無可戀

廢話少說,先上gif爲敬!

這是一個gif動圖

功能

沒什麼好說的,用上最新版微信,打開“位置”—“發送位置”,萌萌噠,感覺一個樣子有木有,想似度99.99%不是夢

還是循例說一下:
* 定位
* 定位數據地圖標誌並列表顯示
* 移動地圖獲取最新位置信息並顯示
* 提供搜索關鍵字功能
* 一鍵發送獲取具體地址信息經緯度什麼的
* !@#¥%…………&&**()

步驟

前期準備

去高德地圖開發中心,註冊賬號,申請key,下載jar包!@#¥%……&*()
(順便吐槽一下高德的文檔看的真讓人蛋!痛!)

GPS定位

  • 使用高德定位獲取AMapLocation數據
  • 將地圖使用動態般絲滑移動到定位數據頁面顯示
  • 繪製出GPS定位到的Marker標記
  • 使用PoiSearch將定位附近地標信息獲取並顯示在RecycleView當中去

移動地圖畫布

  • 爲綁定的AMap添加OnCameraChangeListener監聽器
  • 移動結束後,來一波Marker標記圖案動畫
  • 利用GeocodeSearch將經緯度逆地址編碼變成PoiItem的文字信息
  • 將PoiItem顯示在RecycleView當中去

貌似看起來也不難吧

這是一隻發春的狗

代碼

直接代碼,都有註釋,穩!

定位主頁代碼

package com.weixin.location;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

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.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
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.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.google.gson.Gson;
import com.weixin.location.adapter.AddressAdapter;
import com.weixin.location.utils.DataConversionUtils;
import com.weixin.location.utils.DatasKey;
import com.weixin.location.utils.OnItemClickLisenter;
import com.weixin.location.utils.SPUtils;

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

public class MainActivity extends AppCompatActivity {

    private MapView mMapView;
    private ImageView mIvBack;
    private ImageView mIvSearch;
    private ImageView mIvLocation;
    private ImageView mIvCenterLocation;
    private Button mBtSend;
    private RecyclerView mRecyclerView;
    private AddressAdapter mAddressAdapter;
    private List<PoiItem> mList;
    private PoiItem userSelectPoiItem;

    private AMap mAMap;
    private Marker mMarker, mLocationGpsMarker, mSelectByListMarker;
    private UiSettings mUiSettings;
    private PoiSearch mPoiSearch;
    private PoiSearch.Query mQuery;
    private boolean isSearchData = false;//是否搜索地址數據
    private int searchAllPageNum;//Poi搜索最大頁數,可應用於上拉加載更多
    private int searchNowPageNum;//當前poi搜索頁數
    private float zoom = 14;//地圖縮放級別

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();
    private AMapLocation location;
    private AMapLocationListener mAMapLocationListener;

    private onPoiSearchLintener mOnPoiSearchListener;
    private View.OnClickListener mOnClickListener;
    private GeocodeSearch.OnGeocodeSearchListener mOnGeocodeSearchListener;

    private Gson gson;

    private ObjectAnimator mTransAnimator;//地圖中心標誌動態

    private static final int SEARCHREQUESTCODE = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initDatas(savedInstanceState);
        initListener();
        startLocation();
    }

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

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null != data && SEARCHREQUESTCODE == requestCode) {
            try {
                userSelectPoiItem = (PoiItem) data.getParcelableExtra(DatasKey.SEARCH_INFO);
                if (null != userSelectPoiItem) {
                    isSearchData = false;
                    doSearchQuery(true, "", location.getCity(), userSelectPoiItem.getLatLonPoint());
                    moveMapCamera(userSelectPoiItem.getLatLonPoint().getLatitude(), userSelectPoiItem.getLatLonPoint().getLongitude());
//                    refleshMark(userSelectPoiItem.getLatLonPoint().getLatitude(), userSelectPoiItem.getLatLonPoint().getLongitude());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopLocation();
        mMapView.onDestroy();
        if (null != mPoiSearch) {
            mPoiSearch = null;
        }
        if (null != gson) {
            gson = null;
        }
        if (null != locationClient) {
            locationClient.onDestroy();
        }
    }

    private void initView() {
        mMapView = (MapView) findViewById(R.id.map);
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mIvSearch = (ImageView) findViewById(R.id.iv_search);
        mIvLocation = (ImageView) findViewById(R.id.iv_location);
        mIvCenterLocation = (ImageView) findViewById(R.id.iv_center_location);
        mBtSend = (Button) findViewById(R.id.bt_send);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);

    }

    private void initListener() {
        //監測地圖畫面的移動
        mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (null != location && null != cameraPosition && isSearchData) {
                    mIvLocation.setImageResource(R.mipmap.location_gps_black);
                    zoom = cameraPosition.zoom;
                    if (null != mSelectByListMarker) {
                        mSelectByListMarker.setVisible(false);
                    }
                    getAddressInfoByLatLong(cameraPosition.target.latitude, cameraPosition.target.longitude);
                    startTransAnimator();
//                    doSearchQuery(true, "", location.getCity(), new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude));
                }
                if (!isSearchData) {
                    isSearchData = true;
                }
            }

            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }
        });

        //設置觸摸地圖監聽器
        mAMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                isSearchData = true;
            }
        });

        //Poi搜索監聽器
        mOnPoiSearchListener = new onPoiSearchLintener();

        //逆地址搜索監聽器
        mOnGeocodeSearchListener = new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                if (i == 1000) {
                    if (regeocodeResult != null) {
                        userSelectPoiItem = DataConversionUtils.changeToPoiItem(regeocodeResult);
                        if (null != mList) {
                            mList.clear();
                        }
                        mList.addAll(regeocodeResult.getRegeocodeAddress().getPois());
                        if (null != userSelectPoiItem) {
                            mList.add(0, userSelectPoiItem);
                        }
                        mAddressAdapter.setList(mList);
                        mRecyclerView.smoothScrollToPosition(0);
                    }
                }

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        };

        //gps定位監聽器
        mAMapLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation loc) {
                try {
                    if (null != loc) {
                        stopLocation();
                        if (loc.getErrorCode() == 0) {//可在其中解析amapLocation獲取相應內容。
                            location = loc;
                            SPUtils.putString(MainActivity.this, DatasKey.LOCATION_INFO, gson.toJson(location));
                            doWhenLocationSucess();
                        } else {
                            //定位失敗時,可通過ErrCode(錯誤碼)信息來確定失敗的原因,errInfo是錯誤信息,詳見錯誤碼錶。
                            Log.e("AmapError", "location Error, ErrCode:"
                                    + loc.getErrorCode() + ", errInfo:"
                                    + loc.getErrorInfo());

                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };

        //recycleview列表監聽器
        mAddressAdapter.setOnItemClickLisenter(new OnItemClickLisenter() {
            @Override
            public void onItemClick(int position) {
                try {
                    isSearchData = false;
                    mIvLocation.setImageResource(R.mipmap.location_gps_black);
                    moveMapCamera(mList.get(position).getLatLonPoint().getLatitude(), mList.get(position).getLatLonPoint().getLongitude());
                    refleshSelectByListMark(mList.get(position).getLatLonPoint().getLatitude(), mList.get(position).getLatLonPoint().getLongitude());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });

        //控件點擊監聽器
        mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.iv_back:
                        finish();
                        break;
                    case R.id.iv_search:
//                        Toast.makeText(MainActivity.this, "搜索", Toast.LENGTH_SHORT).show();
                        startActivityForResult(new Intent(MainActivity.this, SearchActivity.class), SEARCHREQUESTCODE);
                        break;
                    case R.id.iv_location:
//                        Toast.makeText(MainActivity.this, "定位", Toast.LENGTH_SHORT).show();
                        mIvLocation.setImageResource(R.mipmap.location_gps_green);
                        if (null != mSelectByListMarker) {
                            mSelectByListMarker.setVisible(false);
                        }
                        if (null == location) {
                            startLocation();
                        } else {
                            doWhenLocationSucess();
                        }
                        break;
                    case R.id.bt_send:
                        if (null != mList && 0 < mList.size() && null != mAddressAdapter) {
                            int position = mAddressAdapter.getSelectPositon();
                            if (position < 0) {
                                position = 0;
                            } else if (position > mList.size()) {
                                position = mList.size();
                            }
                            PoiItem poiItem = mList.get(position);
                            Toast.makeText(MainActivity.this, "發送:" + poiItem.getTitle() + "  " + poiItem.getSnippet() + "  " + "緯度:" + poiItem.getLatLonPoint().getLatitude() + "  " + "經度:" + poiItem.getLatLonPoint().getLongitude(), Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        };

        mIvBack.setOnClickListener(mOnClickListener);
        mIvSearch.setOnClickListener(mOnClickListener);
        mIvLocation.setOnClickListener(mOnClickListener);
        mBtSend.setOnClickListener(mOnClickListener);

    }

    private void initDatas(Bundle savedInstanceState) {
        mMapView.onCreate(savedInstanceState);// 此方法必須重寫
        mAMap = mMapView.getMap();

        mUiSettings = mAMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);//是否顯示地圖中放大縮小按鈕
        mUiSettings.setMyLocationButtonEnabled(false); // 是否顯示默認的定位按鈕
        mUiSettings.setScaleControlsEnabled(true);//是否顯示縮放級別
        mAMap.setMyLocationEnabled(false);// 是否可觸發定位並顯示定位層

        mList = new ArrayList<>();
        mAddressAdapter = new AddressAdapter(this, mList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAddressAdapter);

        gson = new Gson();

        mTransAnimator = ObjectAnimator.ofFloat(mIvCenterLocation, "translationY", 0f, -80f, 0f);
        mTransAnimator.setDuration(800);
//        mTransAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    }

    /**
     * 初始化定位
     */
    private void initLocation() {
        if (null == locationClient) {
            //初始化client
            locationClient = new AMapLocationClient(this.getApplicationContext());
            //設置定位參數
            locationClient.setLocationOption(getDefaultOption());
            // 設置定位監聽
            locationClient.setLocationListener(mAMapLocationListener);
        }
    }

    /**
     * 默認的定位參數
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可選,設置定位模式,可選的模式有高精度、僅設備、僅網絡。默認爲高精度模式
        mOption.setGpsFirst(false);//可選,設置是否gps優先,只在高精度模式下有效。默認關閉
        mOption.setHttpTimeOut(30000);//可選,設置網絡請求超時時間。默認爲30秒。在僅設備模式下無效
        mOption.setInterval(2000);//可選,設置定位間隔。默認爲2秒
        mOption.setNeedAddress(true);//可選,設置是否返回逆地理地址信息。默認是true
        mOption.setOnceLocation(false);//可選,設置是否單次定位。默認是false
        mOption.setOnceLocationLatest(false);//可選,設置是否等待wifi刷新,默認爲false.如果設置爲true,會自動變爲單次定位,持續定位時不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可選, 設置網絡請求的協議。可選HTTP或者HTTPS。默認爲HTTP
        mOption.setSensorEnable(false);//可選,設置是否使用傳感器。默認是false
        mOption.setWifiScan(true); //可選,設置是否開啓wifi掃描。默認爲true,如果設置爲false會同時停止主動刷新,停止以後完全依賴於系統刷新,定位位置可能存在誤差
        mOption.setMockEnable(true);//如果您希望位置被模擬,請通過setMockEnable(true);方法開啓允許位置模擬
        return mOption;
    }

    /**
     * 開始定位
     */
    public void startLocation() {
        initLocation();
        // 設置定位參數
        locationClient.setLocationOption(locationOption);
        // 啓動定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     */
    private void stopLocation() {
        if (null != locationClient) {
            locationClient.stopLocation();
        }
    }

    /**
     * 當定位成功需要做的事情
     */
    private void doWhenLocationSucess() {
        isSearchData = false;
        userSelectPoiItem = DataConversionUtils.changeToPoiItem(location);
        doSearchQuery(true, "", location.getCity(), new LatLonPoint(location.getLatitude(), location.getLongitude()));
        moveMapCamera(location.getLatitude(), location.getLongitude());
        refleshLocationMark(location.getLatitude(), location.getLongitude());
    }


    /**
     * 移動動畫
     */
    private void startTransAnimator() {
        if (null != mTransAnimator && !mTransAnimator.isRunning()) {
            mTransAnimator.start();
        }
    }

    /**
     * 把地圖畫面移動到定位地點(使用moveCamera方法沒有動畫效果)
     *
     * @param latitude
     * @param longitude
     */
    private void moveMapCamera(double latitude, double longitude) {
        if (null != mAMap) {
            mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), zoom));
        }
    }

    /**
     * 刷新地圖標誌物位置
     *
     * @param latitude
     * @param longitude
     */
    private void refleshMark(double latitude, double longitude) {
        if (mMarker == null) {
            mMarker = mAMap.addMarker(new MarkerOptions()
                    .position(new LatLng(latitude, longitude))
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), android.R.color.transparent)))
                    .draggable(true));
        }
        mMarker.setPosition(new LatLng(latitude, longitude));
        mAMap.invalidate();

    }

    /**
     * 刷新地圖標誌物gps定位位置
     *
     * @param latitude
     * @param longitude
     */
    private void refleshLocationMark(double latitude, double longitude) {
        if (mLocationGpsMarker == null) {
            mLocationGpsMarker = mAMap.addMarker(new MarkerOptions()
                    .position(new LatLng(latitude, longitude))
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.mipmap.location_blue)))
                    .draggable(true));
        }
        mLocationGpsMarker.setPosition(new LatLng(latitude, longitude));
        mAMap.invalidate();

    }

    /**
     * 刷新地圖標誌物選中列表的位置
     *
     * @param latitude
     * @param longitude
     */
    private void refleshSelectByListMark(double latitude, double longitude) {
        if (mSelectByListMarker == null) {
            mSelectByListMarker = mAMap.addMarker(new MarkerOptions()
                    .position(new LatLng(latitude, longitude))
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.mipmap.location_red)))
                    .draggable(true));
        }
        mSelectByListMarker.setPosition(new LatLng(latitude, longitude));
        if (!mSelectByListMarker.isVisible()) {
            mSelectByListMarker.setVisible(true);
        }
        mAMap.invalidate();

    }

    /**
     * 開始進行poi搜索
     *
     * @param isReflsh 是否爲刷新數據
     * @param keyWord
     * @param city
     * @param lpTemp
     */
    protected void doSearchQuery(boolean isReflsh, String keyWord, String city, LatLonPoint lpTemp) {
        mQuery = new PoiSearch.Query(keyWord, "", city);//第一個參數表示搜索字符串,第二個參數表示poi搜索類型,第三個參數表示poi搜索區域(空字符串代表全國)
        mQuery.setPageSize(30);// 設置每頁最多返回多少條poiitem
        if (isReflsh) {
            searchNowPageNum = 0;
        } else {
            searchNowPageNum++;
        }
        if (searchNowPageNum > searchAllPageNum) {
            return;
        }
        mQuery.setPageNum(searchNowPageNum);// 設置查第一頁


        mPoiSearch = new PoiSearch(this, mQuery);
        mOnPoiSearchListener.IsReflsh(isReflsh);
        mPoiSearch.setOnPoiSearchListener(mOnPoiSearchListener);
        if (lpTemp != null) {
            mPoiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 10000, true));//該範圍的中心點-----半徑,單位:米-----是否按照距離排序
        }
        mPoiSearch.searchPOIAsyn();// 異步搜索
    }


    /**
     * 通過經緯度獲取當前地址詳細信息,逆地址編碼
     *
     * @param latitude
     * @param longitude
     */
    private void getAddressInfoByLatLong(double latitude, double longitude) {
        GeocodeSearch geocodeSearch = new GeocodeSearch(this);
        /*
        point - 要進行逆地理編碼的地理座標點。
        radius - 查找範圍。默認值爲1000,取值範圍1-3000,單位米。
        latLonType - 輸入參數座標類型。包含GPS座標和高德座標。 可以參考RegeocodeQuery.setLatLonType(String)
        */
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(latitude, longitude), 3000, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
        geocodeSearch.setOnGeocodeSearchListener(mOnGeocodeSearchListener);
    }


    //重寫Poi搜索監聽器,可擴展上拉加載數據,下拉刷新
    class onPoiSearchLintener implements PoiSearch.OnPoiSearchListener {
        private boolean isReflsh;//是爲下拉刷新,否爲上拉加載更多

        public void IsReflsh(boolean isReflsh) {
            this.isReflsh = isReflsh;
        }

        @Override
        public void onPoiSearched(PoiResult result, int i) {
            if (i == 1000) {
                if (result != null && result.getQuery() != null) {// 搜索poi的結果
                    searchAllPageNum = result.getPageCount();
                    if (result.getQuery().equals(mQuery)) {// 是否是同一條
                        if (isReflsh && null != mList) {
                            mList.clear();
                            if (null != userSelectPoiItem) {
                                mList.add(0, userSelectPoiItem);
                            }
                        }
                        mList.addAll(result.getPois());// 取得第一頁的poiitem數據,頁數從數字0開始
                        if (null != mAddressAdapter) {
                            mAddressAdapter.setList(mList);
                            mRecyclerView.smoothScrollToPosition(0);
                        }
                    }
                }
            }
        }

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

        }
    }

}

搜索頁代碼

package com.weixin.location;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.google.gson.Gson;
import com.weixin.location.adapter.SearchAddressAdapter;
import com.weixin.location.utils.DatasKey;
import com.weixin.location.utils.OnItemClickLisenter;
import com.weixin.location.utils.SPUtils;

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

public class SearchActivity extends AppCompatActivity {

    private ImageView mIvBack;
    private EditText mEtSearch;
    private RecyclerView mRecyclerView;
    private List<PoiItem> mList;
    private SearchAddressAdapter mSearchAddressAdapter;

    private PoiSearch mPoiSearch;
    private PoiSearch.Query mQuery;
    private PoiSearch.OnPoiSearchListener mOnPoiSearchListener;

    private View.OnClickListener mOnClickListener;
    private OnItemClickLisenter mOnItemClickLisenter;

    private Gson gson;
    public AMapLocation location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        initDatas();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null == location) {
            String s = SPUtils.getString(this, DatasKey.LOCATION_INFO);//獲取保存的定位信息
            if (!TextUtils.isEmpty(s)) {
                try {
                    location = gson.fromJson(s, AMapLocation.class);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPoiSearch) {
            mPoiSearch = null;
        }
    }

    private void initView() {
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mEtSearch = (EditText) findViewById(R.id.et_search);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    }

    private void initDatas() {
        mList = new ArrayList<>();
        mSearchAddressAdapter = new SearchAddressAdapter(this, mList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mSearchAddressAdapter);

        gson = new Gson();
    }

    private void initListener() {

        mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.iv_back:
                        finish();
                        break;
                }
            }
        };
        mIvBack.setOnClickListener(mOnClickListener);

        mEtSearch.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) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (null != editable) {
                    if (0 == editable.length()) {//沒有輸入則清空搜索記錄
                        mList.clear();
                        mSearchAddressAdapter.setList(mList, "");
                    } else {
                        if (null != location) {
                            doSearchQuery(editable.toString(), location.getCity(), new LatLonPoint(location.getLatitude(), location.getLongitude()));
                        } else {
                            doSearchQuery(editable.toString(), "", null);
                        }
                    }
                }
            }
        });

        mOnItemClickLisenter = new OnItemClickLisenter() {
            @Override
            public void onItemClick(int position) {
                PoiItem poiItem = mList.get(position);
                if (null != poiItem) {//獲取信息並回傳上一頁面
                    Intent intent = new Intent();
                    intent.putExtra(DatasKey.SEARCH_INFO, poiItem);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        };
        mSearchAddressAdapter.setOnItemClickLisenter(mOnItemClickLisenter);

        mOnPoiSearchListener = new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult result, int i) {
                if (i == 1000) {
                    if (result != null && result.getQuery() != null) {// 搜索poi的結果
                        if (result.getQuery().equals(mQuery)) {// 是否是同一條
                            if (null != mList) {
                                mList.clear();
                            }
                            mList.addAll(result.getPois());// 取得第一頁的poiitem數據,頁數從數字0開始
                            if (null != mSearchAddressAdapter) {
                                mSearchAddressAdapter.setList(mList, mEtSearch.getText().toString().trim());
                                mRecyclerView.smoothScrollToPosition(0);
                            }
                        }
                    }
                }
            }

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

            }
        };

    }

    /**
     * 開始進行poi搜索
     */
    protected void doSearchQuery(String keyWord, String city, LatLonPoint lpTemp) {
        mQuery = new PoiSearch.Query(keyWord, "", city);//第一個參數表示搜索字符串,第二個參數表示poi搜索類型,第三個參數表示poi搜索區域(空字符串代表全國)
        mQuery.setPageSize(20);// 設置每頁最多返回多少條poiitem
        mQuery.setPageNum(0);// 設置查第一頁


        mPoiSearch = new PoiSearch(this, mQuery);
        mPoiSearch.setOnPoiSearchListener(mOnPoiSearchListener);
        if (lpTemp != null) {
            mPoiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 10000, true));//該範圍的中心點-----半徑,單位:米-----是否按照距離排序
        }
        mPoiSearch.searchPOIAsyn();// 異步搜索
    }

}

結束

更多詳情,請前往我的github去擼
https://github.com/xiaofuchen/WeixinLocation

順手給Stars是中華人民的美德
謝謝
送美女一枚

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章