微信发送位置源码

   2016-11-03 0
核心提示:科技评论如今的手机已经泛滥,谁都去做手机,做家具的也去做手机,的确,手机变得很重要,手机的重要直接带来的就是手机内部应用和服务的升级,APP也是服务的一种,人们都说软件已经走下滑路线,再加上,微信小程序的出现,更是加剧了软件淡化的趋势,其实,

科技评论

如今的手机已经泛滥,谁都去做手机,做家具的也去做手机,的确,手机变得很重要,手机的重要直接带来的就是手机内部应用和服务的升级,APP也是服务的一种,人们都说软件已经走下滑路线,再加上,微信小程序的出现,更是加剧了软件淡化的趋势,其实,微信的小程序的确可以代替一部分软件,但是最终还是代替不了软件,就像小程序永远都不会代替微信它本身,也有一部分企业已经开发出自己的小程序,准备借势大展宏图,究竟效果怎样,到时我们就知道了,说到底它的最终模式还是一个像应用市场一样的东西,对于技术来讲,Android需求没有以前那么大了,不是因为小程序来了,而是时代快要变了,另一个势头我们都很期待。

效果演示

实现的功能

  1. 根据经纬度定位
  2. 根据所在的经纬度搜索附近的地点
  3. 根据关键字搜索地点
  4. 为地图增加标记
  5. 发送选择的地点位置信息

你能学到什么

  1. 高德地图的使用
  2. 如何定位(获取当前位置信息)
  3. 如何通过经纬度搜索附近的地点(也叫兴趣点poi)
  4. 如何通过关键字搜索附近的兴趣点

微信位置发送分析

  1. 进入发送页面后,自己当前位置有一个蓝色标记,它是不会变的,在蓝色的标记上有一个红色的小钉子,是用来显示你想要定位定到哪去,它在地图的中央
  2. 地图下面有一个列表,是根据当前的经纬度搜索出来的兴趣点,也叫poi,默认选中第一个条目,也就是当前的位置
  3. 当你点击列表的条目时,此时地图会根据你点击的条目变换到你所点击的地点去,此时,被点击的条目被选中
  4. 当你手动的移动地图的时候,中间的红色小钉,不会动,当你移动完地图之后,红色小红钉会有一个上下移动的动画,表示你要定位到红色小红钉处,此时根据小红钉所处的经纬度来搜索附近的兴趣点(poi)
  5. 进入搜索页面之后,通过关键字搜索地点,搜索完成之后,展示在列表里,默认选中第一个,点击条目之后,根据经纬度继续搜索附近的poi,此时列表的第一项是被点击的条目,地图同时移动到被点击的地点处
  6. 点击发送后拿到当前被选中的条目的位置信息,然后发送

分析完了微信的,下面就开始我们自己的,跟着我走,实现你自己想要的模样吧

代码实现及步骤

1. 首页获取定位信息

public class MapUtils implements AMapLocationListener {
        private AMapLocationClient locationClient = null;  // 定位
        private AMapLocationClientOption locationOption = null;  // 定位设置

        @Override
        public void onLocation
Changed(AMapLocation aMapLocation) {
            mLonLatListener.getLonLat(aMapLocation);
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }

        private LonLatListener mLonLatListener;

        public void getLonLat(Context context, LonLatListener lonLatListener) {
            locationClient = new AMapLocationClient(context);
            locationOption = new AMapLocationClientOption();
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);// 设置定位模式为高精度模式
            locationClient.setLocationListener(this);// 设置定位监听
            locationOption.setOnceLocation(false); // 单次定位 每隔2秒定位一次
            locationOption.setNeedAddress(true);//返回地址信息
            mLonLatListener = lonLatListener;//接口
            locationClient.setLocationOption(locationOption);// 设置定位参数
            locationClient.startLocation(); // 启动定位
        }

        public interface LonLatListener {
            void getLonLat(AMapLocation aMapLocation);
        }

    }

2. 逆地理编码,经纬度转换

逆地理编码步骤:

  1. 创建GeocodeSearch实例
    geocoderSearch = new GeocodeSearch(getApplicationContext());
  1. 实现GeocodeSearch.OnGeocodeSearchListener监听
//设置逆地理编码监听
        geocoderSearch.setOnGeocodeSearchListener(this);


          /**
             * 逆地理编码查询回调
             *
             * @param result
             * @param i
             */
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int i) {

                if (i == 1000) {//转换成功
                    if (result != null && result.getRegeocodeAddress() != null
                            && result.getRegeocodeAddress().getFormatAddress() != null) {
                        //拿到详细地址
                        addressName = result.getRegeocodeAddress().getFormatAddress(); // 逆转地里编码不是每次都可以得到对应地图上的opi

                        //条目中第一个地址 也就是当前你所在的地址
                        mAddressInfoFirst = new SearchAddressInfo(addressName, addressName, false, convertToLatLonPoint(mFinalChoosePosition));

                        //其实也是可以在这就能拿到附近的兴趣点的

                    } else {
                        ToastUtil.show(this, "没有搜到");
                    }
                } else {
                    ToastUtil.showerror(this, i);
                }

            }

            /**
             * 地理编码查询回调
             *
             * @param geocodeResult
             * @param i
             */
            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }

通过RegeocodeResult拿到编码后的信息

3. 通过经纬度信息搜索poi

/**
     * 开始进行poi搜索
     * 通过经纬度获取附近的poi信息
     * <p>
     * 1、keyword 传 ""
     * 2、poiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 5000, true)); 根据
     */
    protected void doSearchQueryByPosition() {

        currentPage = 0;
        query = new PoiSearch.Query("", "", city);// 第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国)
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页

        LatLonPoint llPoint = convertToLatLonPoint(mFinalChoosePosition);

        if (llPoint != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);  // 实现  onPoiSearched  和  onPoiItemSearched
            poiSearch.setBound(new PoiSearch.SearchBound(llPoint, 5000, true));//
            // 设置搜索区域为以lpTemp点为圆心,其周围5000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }

4. 通过关键字搜索poi

/**
     * 按照关键字搜索附近的poi信息
     *
     * @param key
     */
    protected void doSearchQueryByKeyWord(String key) {
        currentPage = 0;
        query = new PoiSearch.Query(key, "", city);// 第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国)
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        query.setCityLimit(true); //限定城市

        if (lp != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);   // 实现  onPoiSearched  和  onPoiItemSearched
            poiSearch.setBound(new PoiSearch.SearchBound(lp, 5000, true));//
            // 设置搜索区域为以latLonPoint点为圆心,其周围5000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }

通过poiSearch.setOnPoiSearchListener(this)实现对搜索结果的监听,在onPoiSearched(),onPoiItemSearched()回调里处理返回的结果

5. 处理拿到的poi信息

@Override
        public void onPoiSearched(PoiResult result, int rcode) {

            if (rcode == 1000) {
                if (result != null && result.getQuery() != null) {// 搜索poi的结果
                    if (result.getQuery().equals(query)) {// 是否是同一条
                        poiResult = result;
                        poiItems = poiResult.getPois();// 取得第一页的poiitem数据,页数从数字0开始

                        List<SuggestionCity> suggestionCities = poiResult
                                .getSearchSuggestionCitys();// 当搜索不到poiitem数据时,会返回含有搜索关键字的城市信息

                        //搜索到数据
                        if (poiItems != null && poiItems.size() > 0) {

                            mData.clear();

                            //先将 逆地理编码过的当前地址 也就是条目中第一个地址 放到集合中
                            mData.add(mAddressInfoFirst);

                            SearchAddressInfo addressInfo = null;

                            for (PoiItem poiItem : poiItems) {

                                addressInfo = new SearchAddressInfo(poiItem.getTitle(), poiItem.getSnippet(), false, poiItem.getLatLonPoint());

                                mData.add(addressInfo);
                            }
                            if (isHandDrag) {
                                mData.get(0).isChoose = true;
                            }
                            addressAdapter.notifyDataSetChanged();

                        } else if (suggestionCities != null
                                && suggestionCities.size() > 0) {
                            showSuggestCity(suggestionCities);
                        } else {
                            ToastUtil.show(ShareLocationActivity.this,
                                    "对不起,没有搜索到相关数据");
                        }
                    }
                } else {
                    Toast.makeText(this, "对不起,没有搜索到相关数据!", Toast.LENGTH_SHORT).show();
                }
            }

        }

6. 移动地图

  1. 设置监听
//对amap添加移动地图事件监听器
     aMap.setOnCameraChangeListener(this);
  1. 实现监听
/**
             * 移动地图时调用
             *
             * @param cameraPosition
             */
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            /**
             * 地图移动结束后调用
             *
             * @param cameraPosition
             */
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {

                //每次移动结束后地图中心的经纬度
                mFinalChoosePosition = cameraPosition.target;

                centerImage.startAnimation(centerAnimation);


                if (isHandDrag || isFirstLoad) {//手动去拖动地图

                    // 开始进行poi搜索
                    getAddressFromLonLat(cameraPosition.target);
                    doSearchQueryByPosition();

                } else if (isBackFromSearch) {
                    //搜索地址返回后 拿到选择的位置信息继续搜索附近的兴趣点
                    isBackFromSearch = false;
                    doSearchQueryByPosition();
                } else {
                    addressAdapter.notifyDataSetChanged();
                }
                isHandDrag = true;
                isFirstLoad = false;
            }

7. 分享页面的完整代码

public class ShareLocationActivity extends Activity implements GeocodeSearch.OnGeocodeSearchListener, AMap.OnMapClickListener, AMap.OnCameraChangeListener, PoiSearch.OnPoiSearchListener, AdapterView.OnItemClickListener, View.OnClickListener {

        private String addressName;
        private GeocodeSearch geocoderSearch;
        private MapView mapView;
        private ListView listView;
        private LatLonPoint latLonPoint;
        private AMap aMap;
        private Marker locationMarker;
        private LatLng mFinalChoosePosition;
        private ImageView centerImage;
        private Animation centerAnimation;
        private int currentPage = 0;// 当前页面,从0开始计数
        private PoiSearch.Query query;// Poi查询条件类
        private PoiSearch poiSearch;
        private String city;
        private PoiResult poiResult; // poi返回的结果
        private List<PoiItem> poiItems;// poi数据
        private ArrayList<SearchAddressInfo> mData = new ArrayList<>();
        public SearchAddressInfo mAddressInfoFirst = null;
        private boolean isHandDrag = true;
        private boolean isFirstLoad = true;
        private boolean isBackFromSearch = false;
        private AddressAdapter addressAdapter;
        private UiSettings uiSettings;
        private ImageButton locationButton;
        private ImageView search;
        private TextView send;
        private ImageView back;
        private static final int SEARCH_ADDDRESS = 1;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_share_location);

            double longitude = getIntent().getDoubleExtra("longitude", 0);
            double latitude = getIntent().getDoubleExtra("latitude", 0);
            city = getIntent().getStringExtra("cityCode");

            //经纬度信息
            latLonPoint = new LatLonPoint(latitude, longitude);

            mapView = (MapView) findViewById(R.id.mapview);
            listView = (ListView) findViewById(R.id.listview);
            centerImage = (ImageView) findViewById(R.id.center_image);
            locationButton = (ImageButton) findViewById(R.id.position_btn);
            search = (ImageView) findViewById(R.id.seach);
            send = (TextView) findViewById(R.id.send);
            back = (ImageView) findViewById(R.id.base_back);

            search.setOnClickListener(this);
            send.setOnClickListener(this);
            back.setOnClickListener(this);

            locationButton.setOnClickListener(this);

            mapView.onCreate(savedInstanceState);

            centerAnimation = AnimationUtils.loadAnimation(this, R.anim.center_anim);
            addressAdapter = new AddressAdapter(this, mData);
            listView.setAdapter(addressAdapter);

            listView.setOnItemClickListener(this);
            initMap();

        }

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

        @Override
        public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
            super.onSaveInstanceState(outState, outPersistentState);
            mapView.onSaveInstanceState(outState);
        }

        private void initMap() {

            if (aMap == null) {
                aMap = mapView.getMap();

                //地图ui界面设置
                uiSettings = aMap.getUiSettings();

                //地图比例尺的开启
                uiSettings.setScaleControlsEnabled(true);

                //关闭地图缩放按钮 就是那个加号 和减号
                uiSettings.setZoomControlsEnabled(false);

                aMap.setOnMapClickListener(this);

                //对amap添加移动地图事件监听器
                aMap.setOnCameraChangeListener(this);

                locationMarker = aMap.addMarker(new MarkerOptions()
                        .anchor(0.5f, 0.5f)
                        .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.marker)))
                        .position(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude())));

                //拿到地图中心的经纬度
                mFinalChoosePosition = locationMarker.getPosition();
            }

            setMap();
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()), 20));
        }

        private void setMap() {

            geocoderSearch = new GeocodeSearch(getApplicationContext());

            //设置逆地理编码监听
            geocoderSearch.setOnGeocodeSearchListener(this);
        }

        /**
         * 根据经纬度得到地址
         */
        public void getAddressFromLonLat(final LatLng latLonPoint) {
            // 第一个参数表示一个Latlng,第二参数表示范围多少米,第三个参数表示是火系坐标系还是GPS原生坐标系
            RegeocodeQuery query = new RegeocodeQuery(convertToLatLonPoint(latLonPoint), 200, GeocodeSearch.AMAP);
            geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
        }

        /**
         * 把LatLng对象转化为LatLonPoint对象
         */
        public static LatLonPoint convertToLatLonPoint(LatLng latlon) {
            return new LatLonPoint(latlon.latitude, latlon.longitude);
        }

        /**
         * 把LatLonPoint对象转化为LatLon对象
         */
        public LatLng convertToLatLng(LatLonPoint latLonPoint) {
            return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
        }

        /**
         * 逆地理编码查询回调
         *
         * @param result
         * @param i
         */
        @Override
        public void onRegeocodeSearched(RegeocodeResult result, int i) {

            if (i == 1000) {//转换成功
                if (result != null && result.getRegeocodeAddress() != null
                        && result.getRegeocodeAddress().getFormatAddress() != null) {
                    //拿到详细地址
                    addressName = result.getRegeocodeAddress().getFormatAddress(); // 逆转地里编码不是每次都可以得到对应地图上的opi

                    //条目中第一个地址 也就是当前你所在的地址
                    mAddressInfoFirst = new SearchAddressInfo(addressName, addressName, false, convertToLatLonPoint(mFinalChoosePosition));

                    //其实也是可以在这就能拿到附近的兴趣点的

                } else {
                    ToastUtil.show(this, "没有搜到");
                }
            } else {
                ToastUtil.showerror(this, i);
            }

        }

        /**
         * 地理编码查询回调
         *
         * @param geocodeResult
         * @param i
         */
        @Override
        public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

        }

        @Override
        public void onMapClick(LatLng latLng) {
            Toast.makeText(this, "latitude" + String.valueOf(latLng.latitude), Toast.LENGTH_SHORT).show();
        }

        /**
         * 移动地图时调用
         *
         * @param cameraPosition
         */
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {

        }

        /**
         * 地图移动结束后调用
         *
         * @param cameraPosition
         */
        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {

            //每次移动结束后地图中心的经纬度
            mFinalChoosePosition = cameraPosition.target;

            centerImage.startAnimation(centerAnimation);


            if (isHandDrag || isFirstLoad) {//手动去拖动地图

                // 开始进行poi搜索
                getAddressFromLonLat(cameraPosition.target);
                doSearchQueryByPosition();

            } else if (isBackFromSearch) {
                //搜索地址返回后 拿到选择的位置信息继续搜索附近的兴趣点
                isBackFromSearch = false;
                doSearchQueryByPosition();
            } else {
                addressAdapter.notifyDataSetChanged();
            }
            isHandDrag = true;
            isFirstLoad = false;
        }

        /**
         * 开始进行poi搜索
         * 通过经纬度获取附近的poi信息
         * <p>
         * 1、keyword 传 ""
         * 2、poiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 5000, true)); 根据
         */
        protected void doSearchQueryByPosition() {

            currentPage = 0;
            query = new PoiSearch.Query("", "", city);// 第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国)
            query.setPageSize(20);// 设置每页最多返回多少条poiitem
            query.setPageNum(currentPage);// 设置查第一页

            LatLonPoint llPoint = convertToLatLonPoint(mFinalChoosePosition);

            if (llPoint != null) {
                poiSearch = new PoiSearch(this, query);
                poiSearch.setOnPoiSearchListener(this);  // 实现  onPoiSearched  和  onPoiItemSearched
                poiSearch.setBound(new PoiSearch.SearchBound(llPoint, 5000, true));//
                // 设置搜索区域为以lpTemp点为圆心,其周围5000米范围
                poiSearch.searchPOIAsyn();// 异步搜索
            }
        }

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

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

        @Override
        public void onPoiSearched(PoiResult result, int rcode) {

            if (rcode == 1000) {
                if (result != null && result.getQuery() != null) {// 搜索poi的结果
                    if (result.getQuery().equals(query)) {// 是否是同一条
                        poiResult = result;
                        poiItems = poiResult.getPois();// 取得第一页的poiitem数据,页数从数字0开始

                        List<SuggestionCity> suggestionCities = poiResult
                                .getSearchSuggestionCitys();// 当搜索不到poiitem数据时,会返回含有搜索关键字的城市信息

                        //搜索到数据
                        if (poiItems != null && poiItems.size() > 0) {

                            mData.clear();

                            //先将 逆地理编码过的当前地址 也就是条目中第一个地址 放到集合中
                            mData.add(mAddressInfoFirst);

                            SearchAddressInfo addressInfo = null;

                            for (PoiItem poiItem : poiItems) {

                                addressInfo = new SearchAddressInfo(poiItem.getTitle(), poiItem.getSnippet(), false, poiItem.getLatLonPoint());

                                mData.add(addressInfo);
                            }
                            if (isHandDrag) {
                                mData.get(0).isChoose = true;
                            }
                            addressAdapter.notifyDataSetChanged();

                        } else if (suggestionCities != null
                                && suggestionCities.size() > 0) {
                            showSuggestCity(suggestionCities);
                        } else {
                            ToastUtil.show(ShareLocationActivity.this,
                                    "对不起,没有搜索到相关数据");
                        }
                    }
                } else {
                    Toast.makeText(this, "对不起,没有搜索到相关数据!", Toast.LENGTH_SHORT).show();
                }
            }

        }

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

        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            mFinalChoosePosition = convertToLatLng(mData.get(position).latLonPoint);
            for (int i = 0; i < mData.size(); i++) {
                mData.get(i).isChoose = false;
            }
            mData.get(position).isChoose = true;

            isHandDrag = false;

            // 点击之后,改变了地图中心位置, onCameraChangeFinish 也会调用
            // 只要地图发生改变,就会调用 onCameraChangeFinish ,不是说非要手动拖动屏幕才会调用该方法
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mFinalChoosePosition.latitude, mFinalChoosePosition.longitude), 20));
        }

        /**
         * poi没有搜索到数据,返回一些推荐城市的信息
         */
        private void showSuggestCity(List<SuggestionCity> 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";
            }
            ToastUtil.show(this, infomation);
        }

        @Override
        public void onClick(View v) {
            if (v == locationButton) {
                //回到当前位置
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()), 20));
            } else if (v == back) {
                finish();
            } else if (v == search) {

                Intent intent = new Intent(this, SearchAddressActivity.class);
                intent.putExtra("position", mFinalChoosePosition);
                intent.putExtra("city", city);
                startActivityForResult(intent, SEARCH_ADDDRESS);
                isBackFromSearch = false;

            } else if (v == send) {

                sendLocaton();

            }
        }

        private void sendLocaton() {
            SearchAddressInfo addressInfo = null;
            for (SearchAddressInfo info : mData) {
                if (info.isChoose) {
                    addressInfo = info;
                }
            }
            if (addressInfo != null) {

                ToastUtil.show(this, "要发送的数据:"
                        + "\n 经度:" + addressInfo.latLonPoint.getLongitude()
                        + "\n 纬度:" + addressInfo.latLonPoint.getLatitude()
                        + "\n 地址:" + addressInfo.addressName);
            } else {
                ToastUtil.show(this, "请选择地址");
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == SEARCH_ADDDRESS && resultCode == RESULT_OK) {
                SearchAddressInfo info = (SearchAddressInfo) data.getParcelableExtra("position");
                mAddressInfoFirst = info; // 上一个页面传过来的 位置信息
                info.isChoose = true;
                isBackFromSearch = true;
                isHandDrag = false;
                //移动地图
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(info.latLonPoint.getLatitude(), info.latLonPoint.getLongitude()), 20));
            }
        }
    }

8. 搜索页面的完整代码

public class SearchAddressActivity extends AppCompatActivity implements View.OnClickListener, PoiSearch.OnPoiSearchListener, AdapterView.OnItemClickListener {

        private TextView search;
        private EditText content;
        private ListView listView;
        private SearchAdapter adapter;
        private ArrayList<SearchAddressInfo> mData = new ArrayList<>();
        private String searchText;
        private LatLonPoint lp;//
        private PoiResult poiResult; // poi返回的结果
        private List<PoiItem> poiItems;// poi数据
        private int currentPage = 0;// 当前页面,从0开始计数
        private PoiSearch.Query query;// Poi查询条件类
        private PoiSearch poiSearch;
        private String city;
        private ProgressDialog progressDialog;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_search_address);

            LatLng position = getIntent().getParcelableExtra("position");
            city = getIntent().getStringExtra("city");
            lp = new LatLonPoint(position.latitude, position.longitude);

            iniView();
        }

        private void iniView() {
            search = (TextView) findViewById(R.id.btn_search);
            content = (EditText) findViewById(R.id.input_edittext);
            listView = (ListView) findViewById(R.id.listview);

            search.setOnClickListener(this);

            adapter = new SearchAdapter(this, mData);
            listView.setAdapter(adapter);

            listView.setOnItemClickListener(this);

            progressDialog = new ProgressDialog(this);

            progressDialog.setMessage("搜索中...");
        }

        @Override
        public void onClick(View v) {
            if (v == search) {
                dealSearch();
            }
        }

        private void dealSearch() {
            searchText = content.getText().toString().trim();
            if (TextUtils.isEmpty(searchText)) {
                ToastUtil.show(this, "请输入搜索关键字");
                return;
            } else {
                progressDialog.show();
                doSearchQueryByKeyWord(searchText);
            }
        }

        /**
         * 按照关键字搜索附近的poi信息
         *
         * @param key
         */
        protected void doSearchQueryByKeyWord(String key) {
            currentPage = 0;
            query = new PoiSearch.Query(key, "", city);// 第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国)
            query.setPageSize(20);// 设置每页最多返回多少条poiitem
            query.setPageNum(currentPage);// 设置查第一页
            query.setCityLimit(true); //限定城市

            if (lp != null) {
                poiSearch = new PoiSearch(this, query);
                poiSearch.setOnPoiSearchListener(this);   // 实现  onPoiSearched  和  onPoiItemSearched
                poiSearch.setBound(new PoiSearch.SearchBound(lp, 5000, true));//
                // 设置搜索区域为以latLonPoint点为圆心,其周围5000米范围
                poiSearch.searchPOIAsyn();// 异步搜索
            }
        }

        @Override
        public void onPoiSearched(PoiResult result, int rcode) {

            progressDialog.dismiss();

            if (rcode == 1000) {
                if (result != null && result.getQuery() != null) {// 搜索poi的结果
                    if (result.getQuery().equals(query)) {// 是否是同一条
                        poiResult = result;
                        poiItems = poiResult.getPois();// 取得第一页的poiitem数据,页数从数字0开始
                        List<SuggestionCity> suggestionCities = poiResult
                                .getSearchSuggestionCitys();// 当搜索不到poiitem数据时,会返回含有搜索关键字的城市信息

                        if (poiItems.size() == 0) {
                            //没有搜到数据
                            ToastUtil
                                    .show(this, "对不起,没有搜索到相关数据!");
                            return;
                        }
                        mData.clear();
                        SearchAddressInfo addressInfo = null;
                        for (int i = 0; i < poiItems.size(); i++) {
                            PoiItem poiItem = poiItems.get(i);
                            if (i == 0) {
                                addressInfo = new SearchAddressInfo(poiItem.getTitle(), poiItem.getSnippet(), true, poiItem.getLatLonPoint());
                            } else {
                                addressInfo = new SearchAddressInfo(poiItem.getTitle(), poiItem.getSnippet(), false, poiItem.getLatLonPoint());
                            }

                            mData.add(addressInfo);
                        }
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    ToastUtil
                            .show(this, "对不起,没有搜索到相关数据!");
                }
            } else {
                ToastUtil
                        .show(this, "对不起,没有搜索到相关数据!");
            }

        }

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

        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent();
            SearchAddressInfo addressInfo = mData.get(position);
            intent.putExtra("position", addressInfo);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

9. 最后阐述

看到这里,你想要的基本就能实现了

源码链接

Demo apk下载链接

如果这篇文章对你有用,请关注我们的微信公共号:AppCode

扫码即可关注

微信发送位置源码

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

点击排行