实现地图选择地址,附近poi检索等....

地图选点
/**
 * 地址-地图选点
 * 定位->经纬度->转地址信息PoiList
 * 移动地图->中心点经纬度->转地址信息PoiList
 * 关键字搜索->PoiList
 */
public class AddressMapActivity extends AppCompatActivity implements BaiduMap.OnMapStatusChangeListener, OnGetGeoCoderResultListener, OnGetPoiSearchResultListener {

    @BindView(R.id.mAddressMapSearch)
    EditText mSearchContent;
    @BindView(R.id.mAddressMapView)
    MapView mapView;
    @BindView(R.id.mAddressMapRcy1)
    RecyclerView rcy1;
    @BindView(R.id.mAddressMapContentLayout1)
    LinearLayout mContentLayout;
    @BindView(R.id.mAddressMapRcy2)
    RecyclerView rcy2;
    private BaiduMap mBaiduMap;
    private GeoCoder geoCoder;
    private LocationClient mLocClient;
    private MyLocationListener mLocationListener;
    private PoiListAdapter mPoiListAdapter;
    private List<PoiInfo> poiInfos = new ArrayList<>();
    private List<PoiInfo> searchInfos = new ArrayList<>();
    private PoiSearchAdapter mPoiSearchAdapter;
    private String city;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_map);
        ButterKnife.bind(this);

        initContentView1();
        initContentView2();

        startLocation();
    }

    private void initContentView1() {
        mBaiduMap = mapView.getMap();
        MapStatus mapStatus = new MapStatus.Builder().zoom(15).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
        mBaiduMap.setMapStatus(mMapStatusUpdate);
        // 地图状态改变相关监听
        mBaiduMap.setOnMapStatusChangeListener(this);//让MainActivity实现OnMapStatusChangeListener

        // 创建GeoCoder实例对象
        geoCoder = GeoCoder.newInstance();
        // 设置查询结果监听者
        geoCoder.setOnGetGeoCodeResultListener(this);//让MainActivity实现OnGetGeoCoderResultListener

        rcy1.setLayoutManager(new LinearLayoutManager(this));
        rcy1.setHasFixedSize(true);
        mPoiListAdapter = new PoiListAdapter(R.layout.item_poi, poiInfos);
        mPoiListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String name = poiInfos.get(position).name;
                String province = poiInfos.get(position).province;
                String city = poiInfos.get(position).city;
                String area = poiInfos.get(position).area;
                LatLng location = poiInfos.get(position).location;
                L.show("选点列表click---" + poiInfos.get(position).toString());
                if (location == null) {
                    T.show("未获取到该地点经纬度信息,请重新输入");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("name", name);
                intent.putExtra("province", province);
                intent.putExtra("city", city);
                intent.putExtra("area", area);
                intent.putExtra("lat", location.latitude);
                intent.putExtra("lng", location.longitude);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        rcy1.setAdapter(mPoiListAdapter);
    }

    private void initContentView2() {
        //----------------------------poi搜索模块设置,注册搜索事件监听---------------------------//
        rcy2.setLayoutManager(new LinearLayoutManager(this));
        rcy2.setHasFixedSize(true);
        mPoiSearchAdapter = new PoiSearchAdapter(R.layout.item_poi_search, searchInfos);
        mPoiSearchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String name = searchInfos.get(position).name;
                String province = searchInfos.get(position).province;
                String city = searchInfos.get(position).city;
                String area = searchInfos.get(position).area;
                LatLng location = searchInfos.get(position).location;
                L.show("搜索列表click---" + searchInfos.get(position).toString());
                if (location == null) {
                    T.show("未获取到该地点经纬度信息,请重新输入");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("name", name);
                intent.putExtra("province", province);
                intent.putExtra("city", city);
                intent.putExtra("area", area);
                intent.putExtra("lat", location.latitude);
                intent.putExtra("lng", location.longitude);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        rcy2.setAdapter(mPoiSearchAdapter);

        PoiSearch mPoiSearch = PoiSearch.newInstance();
        //让MainActivity实现OnGetPoiSearchResultListener,当系统定位成功则调用onGetPoiResult()方法
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        mSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() <= 0) {
                    return;
                }
                //根据关键字搜索poi信息
                mPoiSearch.searchInCity((new PoiCitySearchOption())
                        .cityLimit(false)
                        .city(city)
                        .keyword(s.toString())
                        .pageCapacity(20));

            }
        });
    }

    // 输入搜索回调
    @Override
    public void onGetPoiResult(PoiResult result) {
        //获取POI检索结果
        if (result == null || result.getAllPoi() == null || result.getAllPoi().size() == 0) {
            T.show(R.string.empty_data);
            return;
        }
        L.show("----------------------当前搜索结果---------------------------");
        for (PoiInfo info : result.getAllPoi()) {
            L.show("当前的搜索信息:" + info.name + " " + info.address);
        }
        searchInfos.clear();
        searchInfos.addAll(result.getAllPoi());
        mPoiSearchAdapter.notifyDataSetChanged();
    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        // 获取地图最后状态改变的中心点
        LatLng cenpt = mapStatus.target;
        L.show("最后停止点:" + cenpt.latitude + "," + cenpt.longitude);
        //将中心点坐标转化为具体位置信息,当转化成功后调用onGetReverseGeoCodeResult()方法
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(cenpt));

    }

    //经纬度转化地址
    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        L.show("中心点转为地址-----" + reverseGeoCodeResult.toString());
        ReverseGeoCodeResult.AddressComponent detail = reverseGeoCodeResult.getAddressDetail();
        String province = detail.province;
        String city = detail.city;
        String area = detail.distance;

        List<PoiInfo> infos = reverseGeoCodeResult.getPoiList();
        for (int i = 0; i < poiInfos.size(); i++) {
            L.show("附近位置:" + poiInfos.get(i).name);
        }

        if (infos != null && !"".equals(infos)) {
            //创建poiAdapter 将获取到的Poi数据传入,更新UI
            poiInfos.clear();
            poiInfos.addAll(infos);
            mPoiListAdapter.notifyDataSetChanged();
        }
    }

    private void startLocation() {
        mBaiduMap.setMyLocationEnabled(true);
        // 定位图层显示方式
        MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, null));
        mLocClient = new LocationClient(this);
        //注册LocationListener监听器
        mLocationListener = new MyLocationListener();
        mLocClient.registerLocationListener(mLocationListener);
        // 定位参数选项
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        // 设置是否需要地址信息,默认为无地址
        option.setIsNeedAddress(true);
        // 设置是否需要返回位置语义化信息,可以在BDLocation.getLocationDescribe()中得到数据,ex:"在天安门附近",
        // 可以用作地址信息的补充
        option.setIsNeedLocationDescribe(true);
        // 设置是否需要返回位置POI信息,可以在BDLocation.getPoiList()中得到数据
        option.setIsNeedLocationPoiList(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        // 设置是否打开gps进行定位
        option.setOpenGps(true);
        // 设置 LocationClientOption
        mLocClient.setLocOption(option);
        // 开始定位
        mLocClient.start();
    }

    class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息,顺时针0-360
                    .direction(location.getDirection())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            mBaiduMap.setMyLocationData(locData);

            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(ll, 18);
            mBaiduMap.animateMapStatus(msu);
            LatLng locationLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            // 获取城市,待会用于POISearch
            city = location.getCity();
            // 发起反地理编码请求(经纬度->地址信息)
            ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption();
            // 设置反地理编码位置坐标
            reverseGeoCodeOption.location(new LatLng(location.getLatitude(), location.getLongitude()));
            geoCoder.reverseGeoCode(reverseGeoCodeOption);

            //只需要打开该页面时定位一次即可,定位成功后关闭定位功能
            mLocClient.stop();
            mBaiduMap.setMyLocationEnabled(false);
        }
    }

    @OnClick({R.id.mAddressMapBack, R.id.mAddressMapSearch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mAddressMapBack:
                onBackPressed();
                break;
            case R.id.mAddressMapSearch:
                mContentLayout.setVisibility(View.GONE);
                rcy2.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (rcy2.getVisibility() == View.VISIBLE) {
            if (KeyboardUtils.isSoftInputVisible(this))
                KeyboardUtils.hideSoftInput(this);
            mContentLayout.setVisibility(View.VISIBLE);
            rcy2.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }
    }

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

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

    @Override
    protected void onDestroy() {
        mLocClient.unRegisterLocationListener(mLocationListener);
        mBaiduMap.setMyLocationEnabled(false);
        mBaiduMap.clear();
        mBaiduMap = null;
        mapView.onDestroy();
        mapView = null;
        super.onDestroy();

    }


    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }


    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:clipToPadding="false"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar style="@style/AppToolbar">

        <ImageView
            android:id="@+id/mAddressMapBack"
            style="@style/AppBackImg"
            android:paddingRight="20dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="12dp"
            android:background="@color/white"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/iv_search"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="6dp"
                android:src="@mipmap/ic_search" />

            <EditText
                android:id="@+id/mAddressMapSearch"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/transparent"
                android:hint="查找小区,大厦,学校"
                android:singleLine="true"
                android:textColor="@color/text_color"
                android:textSize="14sp" />
        </LinearLayout>


    </android.support.v7.widget.Toolbar>

    <LinearLayout
        android:id="@+id/mAddressMapContentLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:fitsSystemWindows="true"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="2"
            android:orientation="vertical"
            android:visibility="visible">

            <com.baidu.mapapi.map.MapView
                android:id="@+id/mAddressMapView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@android:color/transparent"
                android:src="@mipmap/icon_gcoding" />
        </RelativeLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/mAddressMapRcy1"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:cacheColorHint="#00000000"
            android:descendantFocusability="beforeDescendants"
            android:fastScrollEnabled="true"
            android:scrollbars="none" />
    </LinearLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/mAddressMapRcy2"
        android:layout_width="match_parent"
        android:background="@color/pager"
        android:layout_height="match_parent"
        android:visibility="gone" />

</LinearLayout>

附录:

  1. 高仿百度外卖地址添加功能(百度地图拖动定位,poi搜索,设置配送范围
  2. 百度地图SDK
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容