binbinyang-----百度地图拖动定位,显示附近地址poi提示搜索

来源:互联网 发布:笔记本修改mac地址 编辑:程序博客网 时间:2024/04/30 09:44

 先看看效果图





一。配置百度地图

Android Studio工程配置方法

第一步:在工程app/libs目录下放入baidumapapi_vX_X_X.jar包,在src/main/目录下新建jniLibs目录,工程会自动加载src目录下的so动态库,放入libBaiduMapSDK_vX_X_X_X.so如下图所示,注意jar和so的前3位版本号必须一致,并且保证使用一次下载的文件夹中的两个文件,不能不同功能组件的jar或so交叉使用。

Androidstudio1.png

so的配置也可以参考demo给出的目录结构,如下图所示,在app工程路径下,新建libs,并在libs目录下放入对应不同CPU架构的so文件。这样工程并不会自动加载libs下的so,需在gradle编译时,通过加入代码: jniLibs.srcDir 'libs' 来说明so的路径为该libs路径。

Androidstudio2.png

第二步:工程配置还需要把jar包集成到自己的工程中,如图上图所示,放入libs目录下。对于每个jar文件,右键-选择Add As Library,导入到工程中。对应在build.gradle生成工程所依赖的jar文件说明,如图所示:

Androidstudio3.png

jar的配置也可参考eclipse方法,进行以下操作:

菜单栏选择 File —>Project Structure。

在弹出的Project Structure 对话框中, 选择module, 然后点击 Dependencies 选项卡.

点击绿色的加号选择File dependency. 然后选择要添加的jar包即可 完成上边的操作后在app目录下的build.gradle文件中,会有引入的类库,如上图所示。

Android studio工程配置详细请参考官方demo。
这是我项目的LIBS图


二。xml

<?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:clipToPadding="false"    android:fitsSystemWindows="true"    android:orientation="vertical">    <RelativeLayout        android:id="@+id/rl_search"        android:layout_width="match_parent"        android:layout_height="45dp"        android:background="#90d7ec"        android:visibility="visible">        <ImageView            android:id="@+id/iv_left"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentLeft="true"            android:layout_centerVertical="true"            android:layout_marginLeft="6dp"            android:padding="14dp"            android:src="@drawable/arrow_left" />    </RelativeLayout>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="280dp"        android:orientation="vertical"        android:visibility="visible">        <com.baidu.mapapi.map.MapView            android:id="@+id/map"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:onClick="true"/>        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:background="#00000000"            android:src="@drawable/gps_red" />    </RelativeLayout>    <ListView        android:id="@+id/lv_near_address"        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>


listview的item---xml

<?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:orientation="vertical"    android:padding="5dp" >    <LinearLayout        android:id="@+id/locationpois_linearlayout"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_vertical"        android:orientation="horizontal" >        <ImageView            android:id="@+id/iv_gps"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="4dp"            android:src="@drawable/gps_grey" />        <TextView            android:id="@+id/locationpois_name"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="6dp"            android:text="威盛大厦"            android:textColor="#4A4A4A"            android:textSize="14sp" />    </LinearLayout>    <TextView        android:id="@+id/locationpois_address"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="24dp"        android:layout_marginTop="4dp"        android:text="威盛大厦"        android:textColor="#ffa9a9a9"        android:textSize="12sp" /></LinearLayout>



三。拖动界面上的红色坐标图,拖动到某个位置,listview会根据当前经纬度反地理编码拿到附近的地址列表,listview第一个item写的是当前位置,点击item可以拿到坐标点 经纬度

 

public class MapActivity extends Activity implements View.OnClickListener, OnGetSuggestionResultListener,        BaiduMap.OnMapStatusChangeListener, BDLocationListener, OnGetGeoCoderResultListener {    private ImageView iv_left;    protected static final String TAG = "MapActivity——mwork";    private ListView lv_near_address;    private SuggestionSearch mSuggestionSearch = null;    private BaiduMap mBaiduMap = null;    private double latitude;    private double longitude;    private ArrayAdapter<String> sugAdapter = null;    private MapView map;    private MyLocationConfiguration.LocationMode mCurrentMode;    private LocationClient mLocClient;    private GeoCoder geoCoder;    private String city;    private boolean isFirstLoc = true;    private LatLng locationLatLng;    private LatLng ll;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        SDKInitializer.initialize(getApplicationContext());        setContentView(R.layout.activity_map);        initData();    }    private void initData() {        map = (MapView) findViewById(R.id.map);        mBaiduMap = map.getMap();        MapStatus mapStatus = new MapStatus.Builder().zoom(15).build();        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);        mBaiduMap.setMapStatus(mMapStatusUpdate);        // 地图状态改变相关监听        mBaiduMap.setOnMapStatusChangeListener(this);        // 开启定位图层        mBaiduMap.setMyLocationEnabled(true);        // 定位图层显示方式        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, null));        mLocClient = new LocationClient(this);        // 注册定位监听        mLocClient.registerLocationListener(this);        // 定位选项        LocationClientOption option = new LocationClientOption();        /**         * coorType - 取值有3个:         * 返回国测局经纬度坐标系:gcj02         * 返回百度墨卡托坐标系 :bd09         * 返回百度经纬度坐标:bd09ll         */        option.setCoorType("bd09ll");        // 设置是否需要地址信息,默认为无地址        option.setIsNeedAddress(true);        // 设置是否需要返回位置语义化信息,可以在BDLocation.getLocationDescribe()中得到数据,ex:"在天安门附近",        // 可以用作地址信息的补充        option.setIsNeedLocationDescribe(true);        // 设置是否需要返回位置POI信息,可以在BDLocation.getPoiList()中得到数据        option.setIsNeedLocationPoiList(true);        /**         * 设置定位模式 Battery_Saving 低功耗模式 Device_Sensors 仅设备(Gps)模式 Hight_Accuracy         * 高精度模式         */        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);        // 设置是否打开gps进行定位        option.setOpenGps(true);        // 设置扫描间隔,单位是毫秒 当<1000(1s)时,定时定位无效        option.setScanSpan(1000);        // 设置 LocationClientOption        mLocClient.setLocOption(option);        // 开始定位        mLocClient.start();        lv_near_address = (ListView) findViewById(R.id.lv_near_address);        // 初始化搜索模块,注册搜索事件监听        mSuggestionSearch = SuggestionSearch.newInstance();        mSuggestionSearch.setOnGetSuggestionResultListener(this);        sugAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);        iv_left = (ImageView) findViewById(R.id.iv_left);        iv_left.setOnClickListener(this);    }/*     * 接受周边地理位置结果 */    @Override    protected void onDestroy() {        super.onDestroy();        mLocClient.stop();        mBaiduMap.setMyLocationEnabled(false);        map.onDestroy();        if (geoCoder != null) {            geoCoder.destroy();        }        map = null;        mSuggestionSearch.destroy();    }    @Override    protected void onSaveInstanceState(Bundle outState) {        super.onSaveInstanceState(outState);    }    @Override    protected void onRestoreInstanceState(Bundle savedInstanceState) {        super.onRestoreInstanceState(savedInstanceState);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.iv_left:                finish();                break;            default:                break;        }    }    public void onResume() {        super.onResume();        map.onResume();        if (getIntent().getStringExtra("latitude") != null &&                (!"".equals(getIntent().getStringExtra("latitude")))) {            latitude = Double.parseDouble(getIntent().getStringExtra("latitude"));            longitude = Double.parseDouble(getIntent().getStringExtra("longitude"));        }    }    public void onPause() {        super.onPause();        map.onPause();    }    @Override    public void onGetSuggestionResult(SuggestionResult res) {        if (res == null || res.getAllSuggestions() == null) {            return;        }        sugAdapter.clear();        for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {            if (info.key != null)                sugAdapter.add(info.key + " " + info.city + info.district);        }        sugAdapter.notifyDataSetChanged();    }    @Override    public void onMapStatusChange(MapStatus mapStatus) {    }    @Override    public void onMapStatusChangeFinish(MapStatus mapStatus) {        // 地图操作的中心点        LatLng cenpt = mapStatus.target;        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(cenpt));    }    @Override    public void onMapStatusChangeStart(MapStatus mapStatus) {    }    @Override    public void onReceiveLocation(BDLocation bdLocation) {        // 如果bdLocation为空或mapView销毁后不再处理新数据接收的位置        if (bdLocation == null || mBaiduMap == null) {            return;        }        // 定位数据        MyLocationData data = new MyLocationData.Builder()                // 定位精度bdLocation.getRadius()                .accuracy(bdLocation.getRadius())                // 此处设置开发者获取到的方向信息,顺时针0-360                .direction(bdLocation.getDirection())                // 经度                .latitude(bdLocation.getLatitude())                // 纬度                .longitude(bdLocation.getLongitude())                // 构建                .build();        // 设置定位数据        mBaiduMap.setMyLocationData(data);        // 是否是第一次定位        if (isFirstLoc) {            isFirstLoc = false;            ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());            Toast.makeText(MapActivity.this, ll + "", Toast.LENGTH_SHORT).show();            MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(ll, 18);            mBaiduMap.animateMapStatus(msu);        }        locationLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());        // 获取城市,待会用于POISearch        city = bdLocation.getCity();        // 创建GeoCoder实例对象        geoCoder = GeoCoder.newInstance();        // 发起反地理编码请求(经纬度->地址信息)        ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption();        // 设置反地理编码位置坐标        reverseGeoCodeOption.location(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));        geoCoder.reverseGeoCode(reverseGeoCodeOption);        // 设置查询结果监听者        geoCoder.setOnGetGeoCodeResultListener(this);    }    @Override    public void onGetGeoCodeResult(GeoCodeResult arg0) {    }    // 拿到变化地点后的附近地址    @Override    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {        final List<PoiInfo> poiInfos = reverseGeoCodeResult.getPoiList();        Log.i(TAG, "这里的值:" + poiInfos);        if (poiInfos != null && !"".equals(poiInfos)) {            PoiAdapter poiAdapter = new PoiAdapter(MapActivity.this, poiInfos);            mLocClient.stop();            lv_near_address.setAdapter(poiAdapter);            lv_near_address.setOnItemClickListener(new AdapterView.OnItemClickListener() {                @Override                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                    String                            name = poiInfos.get(position).name.toString();                    LatLng latLng = poiInfos.get(position).location;                    double lat = poiInfos.get(position).location.latitude;                    double lon = poiInfos.get(position).location.longitude;                    Toast.makeText(MapActivity.this, name + lat + lon + "", Toast.LENGTH_LONG).show();                    System.out.println(ll + "==" + latLng + "=====" + DistanceUtil.getDistance(ll, latLng) + "===================");                }            });        }    }    /**     * listview列表适配器     */    class PoiAdapter extends BaseAdapter {        private Context context;        private List<PoiInfo> pois;        private LinearLayout linearLayout;        PoiAdapter(Context context, List<PoiInfo> pois) {            this.context = context;            this.pois = pois;        }        @Override        public int getCount() {            return pois.size();        }        @Override        public Object getItem(int position) {            return pois.get(position);        }        @Override        public long getItemId(int position) {            return position;        }        @Override        public View getView(int position, View convertView, ViewGroup parent) {            ViewHolder holder = null;            if (convertView == null) {                convertView = LayoutInflater.from(context).inflate(R.layout.item_locationpois, null);                linearLayout = (LinearLayout) convertView.findViewById(R.id.locationpois_linearlayout);                holder = new ViewHolder(convertView);                convertView.setTag(holder);            } else {                holder = (ViewHolder) convertView.getTag();            }            if (position == 0) {                holder.iv_gps.setImageDrawable(getResources().getDrawable(R.drawable.gps_grey));                holder.locationpoi_name.setTextColor(Color.parseColor("#FF9D06"));                holder.locationpoi_address.setTextColor(Color.parseColor("#FF9D06"));            }            if (position == 0 && linearLayout.getChildCount() < 2) {                ImageView imageView = new ImageView(context);                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(32, 32);                imageView.setLayoutParams(params);                imageView.setBackgroundColor(Color.TRANSPARENT);                imageView.setImageResource(R.drawable.gps_grey);                imageView.setScaleType(ImageView.ScaleType.FIT_XY);                linearLayout.addView(imageView, 0, params);                holder.locationpoi_name.setTextColor(Color.parseColor("#FF5722"));            }            PoiInfo poiInfo = pois.get(position);            holder.locationpoi_name.setText(poiInfo.name);            holder.locationpoi_address.setText(poiInfo.address);            return convertView;        }        class ViewHolder {            ImageView iv_gps;            TextView locationpoi_name;            TextView locationpoi_address;            ViewHolder(View view) {                locationpoi_name = (TextView) view.findViewById(R.id.locationpois_name);                locationpoi_address = (TextView) view.findViewById(R.id.locationpois_address);                iv_gps = (ImageView) view.findViewById(R.id.iv_gps);            }        }    }}

1 0
原创粉丝点击