android studio 百度地图(二)

1.功能需求

1.根据用户输入得到建议地址

2.根据地址得到对应经纬度

3.根据经纬度实现导航

1.实现步骤

1.初始化百度地图

SDKInitializer.initialize(getActivity().getApplicationContext());//百度地图初始化器

2.实现建议搜索与地址转经纬度

1…实现接口重写方法

实现接口:建议接口与地理转码

implements OnGetSuggestionResultListener, OnGetGeoCoderResultListener {//建议回调监听,地理编码

重写方法
在这里插入图片描述
实现自己位置接口

private LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            mCurrentLat = location.getLatitude();//获取自己纬度
            mCurrentLng = location.getLongitude();//自己经度
            Toast.makeText(SearchByTextActivity.this, mCurrentLat
                    + "--" + mCurrentLng, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

2.初始化

控件初始化

// 初始化view                                                                    
mEditCity = (EditText) findViewById(R.id.city);                               
mSugListView = (ListView) findViewById(R.id.sug_list);                        
mKeyWordsView = (AutoCompleteTextView) findViewById(R.id.searchkey);//设置关键字视图 
mKeyWordsView.setThreshold(1);//设置阈值                                          

搜索建议初始化

mSuggestionSearch = SuggestionSearch.newInstance();//实例化建议搜索        
mSuggestionSearch.setOnGetSuggestionResultListener(this);//创建独特的建议监听

地理编码初始化

//地理编码
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);//地理编码监听

3.触发监听

触发自己位置监听

//自己的位置
    private void initLocation1() {
        mLocationManager = (LocationManager) SearchByTextActivity.this.getSystemService(LOCATION_SERVICE);
        if (mLocationManager != null) {
            if (ActivityCompat.checkSelfPermission(SearchByTextActivity.this, Manifest.permission
                    .ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat
                    .checkSelfPermission(SearchByTextActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(SearchByTextActivity.this, "没有权限", Toast.LENGTH_SHORT).show();
                return;
            }
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                    1000, 1000, mLocationListener);
        }
    }

关键字视图KeyWordsView监听触发

// 当输入关键字变化时,动态更新建议列表
        mKeyWordsView.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                if (cs.length() <= 0) {//字符序列小于0
                    return;
                }

                // 使用建议搜索服务获取建议列表,结果在onGetSuggestionResult中更新,即触发监听
                mSuggestionSearch.requestSuggestion(//请求
                        (new SuggestionSearchOption())//搜索选项
                        .keyword(cs.toString()) // 关键字
                        .city(mEditCity.getText().toString()//城市
                        )
                ); 
            }
        });

其中这里就会触发onGetSuggestionResult接口方法

// 使用建议搜索服务获取建议列表,结果在onSuggestionResult()中更新,即触发监听
                mSuggestionSearch.requestSuggestion(//请求
                        (new SuggestionSearchOption())//搜索选项
                        .keyword(cs.toString()) // 关键字
                        .city(mEditCity.getText().toString()//城市
                        )
                );

触发接口:onGetSuggestionResult

    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
        if (suggestionResult == null || suggestionResult.getAllSuggestions() == null) {//判断返回值是否为空
            return;
        }
        //数据遍历,规律化
        suggest = new ArrayList<>();
        for (SuggestionResult.SuggestionInfo info : suggestionResult.getAllSuggestions()) {
            if (info.getKey() != null && info.getDistrict() != null && info.getCity() != null) {
                HashMap<String, String> map = new HashMap<>();
                map.put("key", info.getKey());
                map.put("city", info.getCity());
                map.put("dis", info.getDistrict());
                suggest.add(map);
            }
        }
        Log.d(TAG, "onGetSuggestionResult: "+suggest.toString());
        //设置适配器属性,并建立适配器
        SimpleAdapter simpleAdapter = new SimpleAdapter(getApplicationContext(),
                suggest,
                R.layout.item_layout,
                new String[]{ConstantsUtils.BUNDLE_CITY_KEY, ConstantsUtils.BUNDLE_CITY, ConstantsUtils.BUNDLE_ADDRESS},
//                new String[]{"key", "city","dis"},//注意点,根值一定要这三个值
                new int[]{R.id.sug_key, R.id.sug_city, R.id.sug_dis});
        mSugListView.setAdapter(simpleAdapter);
        simpleAdapter.notifyDataSetChanged();//刷新适配器
        //listView视图监听,点击传入地址值,调用地理编码接口进行编码
        mSugListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bundle bundle=new Bundle();
                String key = suggest.get(i).get(ConstantsUtils.BUNDLE_CITY_KEY);
                String city = suggest.get(i).get(ConstantsUtils.BUNDLE_CITY);
                String address = suggest.get(i).get(ConstantsUtils.BUNDLE_ADDRESS);
                Log.d(TAG, "onItemClick: "+key
                +"\n"+city
                +"\n"+address
                        );
                //根据客户输入得到目的地经纬度,触发监听
                mSearch.geocode(new GeoCodeOption()
                        .city(city)//城市EditText
                        .address(address));//地址EditText
            }
        });
    }

下面是来触发地理编码接口监听

mSearch.geocode(new GeoCodeOption()
                        .city(city)//城市EditText
                        .address(address));//地址EditText

触发接口:onGetGeoCodeResult,onGetReverseGeoCodeResult正反编译

/**
     * 地理编码查询结果回调函数
     *
     * @param geoCodeResult  地理编码查询结果
     */
    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult==null||geoCodeResult.error!= SearchResult.ERRORNO.NO_ERROR) {//如果编码结果为null或不正确
            Toast.makeText(SearchByTextActivity.this, "抱歉,未能收到结果", Toast.LENGTH_SHORT).show();
            return;
        }
        //起始位置
        BNRoutePlanNode sNode = new BNRoutePlanNode.Builder()
        //自己的经纬度位置
                .latitude(mCurrentLat)
                .longitude(mCurrentLng)
                .coordinateType(BNRoutePlanNode.CoordinateType.WGS84)//默认
                .build();
        //终点
        BNRoutePlanNode eNode = new BNRoutePlanNode.Builder()
        //建议搜索编码结果经纬度
                .latitude(geoCodeResult.getLocation().latitude)
                .longitude(geoCodeResult.getLocation().longitude)
                .coordinateType(BNRoutePlanNode.CoordinateType.WGS84)
                .build();
                //开始路线计划导航
        routePlanToNavi(sNode, eNode);//路线规划到导航,起点,终点
    }

    //逆编码监听回调
    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

    }

路线计划导航方法

/**
     * 路线计划导航
     * @param sNode 起点
     * @param eNode 终点
     */
    private void routePlanToNavi(BNRoutePlanNode sNode, BNRoutePlanNode eNode) {
        List<BNRoutePlanNode> list = new ArrayList<>();//路线计划导航list
        list.add(sNode);//加入起点
        list.add(eNode);//加入终点
        //根据指定参数进行路线规划,并自动做好进入导航准备
        BaiduNaviManagerFactory.getRoutePlanManager().routeplanToNavi(
                list,//起止点list
                IBNRoutePlanManager.RoutePlanPreference.ROUTE_PLAN_PREFERENCE_DEFAULT,//路由计划首选项默认
                null,//绑定值为空
                new Handler(Looper.getMainLooper()) {//开启处理程序
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START://信息导航路线开始
                                Toast.makeText(SearchByTextActivity.this.getApplicationContext(),
                                        "算路开始", Toast.LENGTH_SHORT).show();//吐司:
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS:
                                Toast.makeText(SearchByTextActivity.this.getApplicationContext(),
                                        "算路成功", Toast.LENGTH_SHORT).show();
                                // 躲避限行消息
                                Bundle infoBundle = (Bundle) msg.obj;
                                if (infoBundle != null) {
                                    String info = infoBundle.getString(
                                            BNaviCommonParams.BNRouteInfoKey.TRAFFIC_LIMIT_INFO//交通限制信息
                                    );
                                    Log.d("OnSdkDemo", "info = " + info);
                                }
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED://信息导航路线失败
                                Toast.makeText(SearchByTextActivity.this.getApplicationContext(),
                                        "算路失败", Toast.LENGTH_SHORT).show();
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_TO_NAVI://算路成功进入导航,这里已经实现了导航地图
                                Toast.makeText(SearchByTextActivity.this.getApplicationContext(),
                                        "算路成功准备进入导航", Toast.LENGTH_SHORT).show();//吐司

                                Intent intent = new Intent(SearchByTextActivity.this,
                                        GuideActivity.class);//跳转到导航界面
                                startActivity(intent);
                                break;
                            default:
                                // nothing
                                break;
                        }
                    }
                });
    }

记得destroy掉

@Override
    protected void onDestroy() {
        super.onDestroy();
        mbitmap.recycle();
        // 释放检索对象
        mSearch.destroy();
        // 清除所有图层
        mBaiduMap.clear();
        // 在activity执行onDestroy时必须调用mMapView. onDestroy ()
        mMapView.onDestroy();
    }

……未完待续……

猜你喜欢

转载自blog.csdn.net/sunweihao2019/article/details/108144724