Android百度地图显示附近的位置

来源:互联网 发布:java classpath 路径 编辑:程序博客网 时间:2024/04/30 15:12

效果如下图所示,可以使用手滑动上面的地图进行位置刷新,

主要实现思路是去掉原始的地图导航图层,再MapView的正中间放一张图片,给MapView添加手滑动地图的事件进行添加,再获取MapView的中点坐标进行反编码确定位置,获取PoiInfo进行适配器的填充实现效果。

第一步:按照官方文档给出的步骤配置开发环境

第二步:布局界面

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"    tools:context="com.example.view.MainActivity">    <RelativeLayout        android:id="@+id/top_layout"        android:layout_width="match_parent"        android:layout_height="200dp"        >        <com.baidu.mapapi.map.MapView            android:id="@+id/bmapView"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:clickable="true" />        <ImageView            android:id="@+id/marker"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@mipmap/icon_marka"            android:layout_centerVertical="true"            android:layout_centerHorizontal="true" />    </RelativeLayout>    <android.support.v7.widget.RecyclerView        android:id="@+id/id_recyclerview"        android:layout_below="@+id/top_layout"        android:divider="#ffff0000"        android:dividerHeight="10dp"        android:layout_width="match_parent"        android:layout_height="match_parent" /></RelativeLayout>
</pre>整体就是上面一个布局(<span style="background-color:rgb(240,240,240)">MapView和一个ImageView</span>)下面一个RecyclerView<p></p><p>第三步 MainActivity的代码</p><p></p><pre name="code" class="java">public class MainActivity extends AppCompatActivity implements OnGetGeoCoderResultListener {    public LocationClient mLocationClient = null;    public BDLocationListener myListener = new MyLocationListener();    private MapView mMapView;    private GeoCoder mSearch;    private BaiduMap mBaiduMap;    private RecyclerView mRecyclerView;    private MyAdapter adapter;    private List<PoiInfo> mList;    boolean isFirstLoc = true; // 是否首次定位    //    private TextView tv_location;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);//        在使用SDK各组件之前初始化context信息,传入ApplicationContext        //注意该方法要再setContentView方法之前实现        SDKInitializer.initialize(getApplicationContext());        setContentView(R.layout.activity_main);        mRecyclerView= (RecyclerView) findViewById(R.id.id_recyclerview);        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));        mList=new ArrayList<>();        adapter=new MyAdapter(this,mList);        mRecyclerView.setAdapter(adapter);        //获取地图控件引用        mMapView= (MapView) findViewById(R.id.bmapView);        mMapView.showZoomControls(false);        mBaiduMap = mMapView.getMap();        // 开启定位图层        mBaiduMap.setMyLocationEnabled(false);        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类        initLocation();        mLocationClient.registerLocationListener(myListener);    //注册监听函数        mLocationClient.start();        // 初始化搜索模块,注册事件监听        mSearch = GeoCoder.newInstance();        mSearch.setOnGetGeoCodeResultListener(this);        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {            @Override            public void onMapStatusChangeStart(MapStatus arg0) {                // TODO Auto-generated method stub            }            @Override            public void onMapStatusChangeFinish(MapStatus arg0) {                // TODO Auto-generated method stub                LatLng ptCenter = mBaiduMap.getMapStatus().target; //获取地图中心点坐标                // 反Geo搜索                mSearch.reverseGeoCode(new ReverseGeoCodeOption()                        .location(ptCenter));            }            @Override            public void onMapStatusChange(MapStatus arg0) {                // TODO Auto-generated method stub            }        });    }    @Override    protected void onDestroy() {        super.onDestroy();        //在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理        mMapView.onDestroy();    }    @Override    protected void onResume() {        super.onResume();        //在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理        mMapView.onResume();    }    @Override    protected void onPause() {        super.onPause();        //在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理        mMapView.onPause();    }    private void initLocation() {        LocationClientOption option = new LocationClientOption();        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy        );//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备        option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系        int span = 1000;        option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的        option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要        option.setOpenGps(true);//可选,默认false,设置是否使用gps        option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果        option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”        option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到        option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死        option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集        option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要        mLocationClient.setLocOption(option);    }    @Override    public void onGetGeoCodeResult(GeoCodeResult result) {        //设置地图中心点坐标        MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(result.getLocation());        mBaiduMap.animateMapStatus(status);        Toast.makeText(MainActivity.this, result.getAddress(), Toast.LENGTH_LONG).show();    }    @Override    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {            Toast.makeText(MainActivity.this, "抱歉,未能找到结果", Toast.LENGTH_LONG)                    .show();            return;        }        mBaiduMap.clear();        List<PoiInfo> list=result.getPoiList();        mList.clear();        for (int i=0;i<list.size();i++){            mList.add(list.get(i));        }        adapter.notifyDataSetChanged();        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result                .getLocation()));//改变地图状态?//        Toast.makeText(MainActivity.this, result.getAddressDetail().city + "  "+//                        result.getAddressDetail().district +"  "+ result.getAddressDetail().street +//                        result.getAddressDetail().streetNumber,//                Toast.LENGTH_LONG).show();    }    public class MyLocationListener implements BDLocationListener {        @Override        public void onReceiveLocation(BDLocation location) {            // map view 销毁后不在处理新接收的位置            if (location == null || mMapView == null) {                return;            }            MyLocationData locData = new MyLocationData.Builder()                    .accuracy(location.getRadius())                            // 此处设置开发者获取到的方向信息,顺时针0-360                    .direction(100).latitude(location.getLatitude())                    .longitude(location.getLongitude()).build();            mBaiduMap.setMyLocationData(locData);            if (isFirstLoc) {                isFirstLoc = false;                LatLng ll = new LatLng(location.getLatitude(),                        location.getLongitude());                MapStatus.Builder builder = new MapStatus.Builder();                builder.target(ll).zoom(17.0f);//地图缩放级别                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));            }        }    }}
第三步:item_layout布局代码

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="100dp"    ><TextView    android:id="@+id/tv_location"    android:layout_width="match_parent"    android:layout_height="40dp"    android:text="国家软件园"    android:textSize="20dp"    android:layout_marginLeft="20dp"    />    <TextView        android:id="@+id/tv_detail_location"        android:layout_marginTop="10dp"        android:layout_width="match_parent"        android:layout_height="30dp"        android:text="菱湖大道"        android:layout_marginLeft="20dp"        />    <TextView        android:layout_width="match_parent"        android:layout_height="1dp"        android:background="@color/colorBackground"/></LinearLayout>
第四步:适配器MyAdapter的代码
<pre name="code" class="java">public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{    private Context mContext;    private List<PoiInfo> mItems;    private LayoutInflater mInflater;    public MyAdapter( Context mContext,List<PoiInfo> mItems) {        this.mItems = mItems;        this.mContext = mContext;        this.mInflater=LayoutInflater.from(mContext);    }    @Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        View view=mInflater.inflate(R.layout.item_location,parent,false);        return new ViewHolder(view);    }    @Override    public void onBindViewHolder(ViewHolder holder, int position) {        holder.tv_location.setText(mItems.get(position).name);        holder.tv_detail_location.setText(mItems.get(position).address);    }    @Override    public int getItemCount() {        return mItems.size();    }    class ViewHolder extends RecyclerView.ViewHolder{        private TextView tv_location;        private TextView tv_detail_location;        public ViewHolder(View itemView) {            super(itemView);            tv_location= (TextView) itemView.findViewById(R.id.tv_location);            tv_detail_location= (TextView) itemView.findViewById(R.id.tv_detail_location);        }    }}

源码下载地址


0 0