android 百度地圖--根據地址和經緯度搜索

最近做了個應用,裏面用到了百度地圖,具體需求是:

1. 輸入地址,點擊“定位”按鈕,跳轉到百度地圖頁面,搜索並顯示定位點在該地址;

2. 不輸入地址,點擊“定位”按鈕,跳轉到百度地圖,顯示當前位置;

3. 在百度地圖頁面,點擊某一位置,使定位點移動到此處,點擊“確定”,返回經緯度到上一頁面;

4. 根據已有的經緯度,點擊“定位”,跳轉到百度地圖,定位到相應位置;

具體代碼如下:

1.  第一個頁面的xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
            android:background="@drawable/bg_enforce_border"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:text="地址:"
                style="@style/enforce_text_label_style"
                android:layout_gravity="center_vertical"
                android:layout_weight="2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"/>
            <EditText
                android:id="@+id/tv_addr"
                android:text=""
                android:layout_weight="4"
                android:layout_width="0dp"
                android:gravity="right"
                android:background="@color/trans"
                style="@style/enforce_text_style_padding"
                android:layout_marginRight="@dimen/px30"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <LinearLayout
            android:background="@drawable/bg_enforce_border"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:text="經度:"
                style="@style/enforce_text_label_style"
                android:layout_weight="2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/tv_lng"
                android:text=""
                android:layout_weight="4"
                android:layout_width="0dp"
                android:gravity="right"
                style="@style/enforce_text_style"
                android:layout_marginRight="@dimen/px30"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <LinearLayout
            android:background="@drawable/bg_enforce_border"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:text="緯度:"
                style="@style/enforce_text_label_style"
                android:layout_weight="2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"/>
            <RelativeLayout
                android:layout_marginRight="@dimen/px30"
                android:layout_weight="4"
                android:layout_width="0dp"
                android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/tv_lat"
                    android:text=""
                    android:gravity="right"
                    android:paddingRight="@dimen/px30"
                    android:layout_width="match_parent"
                    android:layout_toLeftOf="@+id/btn_local"
                    style="@style/enforce_text_style_padding"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/btn_local"
                    android:text="定位"
                    android:background="@drawable/bg_button_radius_bluedark"
                    android:textColor="@color/colorTextWhite"
                    android:padding="@dimen/px20"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_centerVertical="true" />
            </RelativeLayout>
        </LinearLayout>
</LinearLayout>

2. 頁面代碼:

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_local:
                requestPermission();
                break;
        }
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23 ) {
//            isPermissionRequested = true;
            ArrayList<String> permissionsList = new ArrayList<>();
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };

            for (String perm : permissions) {
                if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(perm)) {
                    permissionsList.add(perm);
                    // 進入到這裏代表沒有權限.
                }
            }

            if (!permissionsList.isEmpty()) {
                Log.e(TAG,"permissionsList.isEmpty()="+permissionsList.isEmpty());
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), 0);
            } else {
                Intent intent = new Intent(mContext, MapForOfficeActivity.class);
                String latStr = tv_lat.getText().toString();
                String lntStr = tv_lng.getText().toString();
                if (latStr != null && !latStr.equals("") && lntStr != null && !lntStr.equals("")) {
                    intent.putExtra("latitude",Double.valueOf(latStr));
                    intent.putExtra("longitude", Double.valueOf(lntStr));
                } else {
                    String addStr = tv_addr.getText().toString();
                    if (addStr != null && !addStr.equals("")) {
                        intent.putExtra("address", addStr);
                    }
                }
                startActivityForResult(intent,2004);
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        super.onPermissionsGranted(requestCode, perms);
        LogUtil.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
        Intent intent = new Intent(mContext, MapForOfficeActivity.class);
        String latStr = tv_lat.getText().toString();
        String lntStr = tv_lng.getText().toString();

        if (latStr != null && !latStr.equals("") && lntStr != null && !lntStr.equals("")) {
            intent.putExtra("latitude",Double.valueOf(latStr));
            intent.putExtra("longitude", Double.valueOf(lntStr));
        } else {
            String addStr = tv_addr.getText().toString();
            if (addStr != null && !addStr.equals("")) {
                intent.putExtra("address", addStr);
            }
        }
        startActivityForResult(intent,2004);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        super.onPermissionsDenied(requestCode, perms);
        LogUtil.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//            //new AppSettingsDialog.Builder(this).build().show();
//            LogUtil.d(TAG, "onPermissionsDenied: denied any permissions");
//            showPermissionDialog();
//        } else {
//        }
        ToastUtils.showMsg("已拒絕相機訪問權限,請重新授權");
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 2004 && resultCode == RESULT_OK) {
            Log.e(TAG,"data="+data.getData()+","+data.getDataString());
            double lat = data.getDoubleExtra("latitude",0);
            double lnt = data.getDoubleExtra("longitude",0);
            String addr = data.getStringExtra("address");
            Log.e(TAG,"addr="+addr);
            tv_lat.setText(String.valueOf(lat));
            tv_lng.setText(String.valueOf(lnt));
        }
    }

3. 地圖頁面 MapForOfficeActivity.java

public class MapForOfficeActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MapForOfficeActivity";

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    public LocationClient mLocClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    boolean isFirstLoc = true; // 是否首次定位
    private double mLatitude;
    private double mLongitude;
    private String mAddress;

    private void initMap() {

        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                MyLocationConfiguration.LocationMode.NORMAL, true, BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding),
                0x0f1679b3, 0xAA00FF00));

        // 開啓定位圖層
        mBaiduMap.setMyLocationEnabled(true);
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打開gps
        option.setIsNeedAddress(true);
        option.setCoorType("bd09ll"); // 設置座標類型
        option.setScanSpan(3000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    @Override
    public void onBeforeSetContentView() {

    }

    @Override
    public int getLayoutResID() {
        return R.layout.activity_map_for_office;
    }

    @Override
    public void initContentView(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mLatitude = getIntent().getDoubleExtra("latitude", 0.0f);
        mLongitude = getIntent().getDoubleExtra("longitude", 0.0f);
        mAddress = getIntent().getStringExtra("address");
        Log.e(TAG,"mAddress="+mAddress);
        if (mAddress != null && !mAddress.equals("")) {
            initSearch();
        }
        initView();
        initMap();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此處的BDLocation爲定位結果信息類,通過它的各種get方法可獲取定位相關的全部結果
            //以下只列舉部分獲取經緯度相關(常用)的結果信息
            //更多結果信息獲取說明,請參照類參考中BDLocation類中的說明
            String province = location.getProvince();    //獲取省份
            String city = location.getCity();    //獲取城市
            String district = location.getDistrict();    //獲取區縣
            String street = location.getStreet();    //獲取街道信息
            mAddress = province + city + district + street;
            //獲取緯度信息
//            mLatitude = location.getLatitude();
//            //獲取經度信息
//            mLongitude = location.getLongitude();
            float radius = location.getRadius();    //獲取定位精度,默認值爲0.0f

            String coorType = location.getCoorType();
            //獲取經緯度座標類型,以LocationClientOption中設置過的座標類型爲準

            int errorCode = location.getLocType();
            //獲取定位類型、定位錯誤返回碼,具體信息可參照類參考中BDLocation類中的說明

            Log.d("flag", "onReceiveLocation: " + mLatitude + ":" + mLongitude + ":" + radius + ":" + errorCode);

            if(mLatitude == 0.0 && mLongitude == 0.0) {
                MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                        // 此處設置開發者獲取到的方向信息,順時針0-360
                        .direction(location.getDirection())
//                    .direction(100)
                    .latitude(location.getLatitude()).longitude(location.getLongitude())
                        .build();
                mLatitude = location.getLatitude();
                mLongitude = location.getLongitude();
                mBaiduMap.setMyLocationData(locData);
            } else {
                MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                        // 此處設置開發者獲取到的方向信息,順時針0-360
                        .direction(location.getDirection())
                        .latitude(mLatitude).longitude(mLongitude)
                        .build();
                mBaiduMap.setMyLocationData(locData);
            }

            if (isFirstLoc) {
                isFirstLoc = false;
//                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                LatLng ll = new LatLng(mLatitude, mLongitude);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }

            // 當不需要定位圖層時關閉定位圖層
//            mBaiduMap.setMyLocationEnabled(false);

        }

    }

    private void initView() {

        TextView title = findViewById(R.id.title);
        title.setText("地圖");
        LinearLayout back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        TextView type_normal = findViewById(R.id.type_normal);
        TextView type_satellite = findViewById(R.id.type_satellite);
        TextView map_position = findViewById(R.id.map_position);
        TextView confirm = findViewById(R.id.confirm);
        type_normal.setOnClickListener(this);
        type_satellite.setOnClickListener(this);
        map_position.setOnClickListener(this);
        confirm.setOnClickListener(this);

        mMapView = findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Log.e(TAG, "onMapClick latitude: "+latLng.latitude );//經度
            }
            @Override
            public void onMapPoiClick(MapPoi mapPoi) {
                Log.e(TAG, "onMapPoiClick latitude: "+mapPoi.getName()+","+mapPoi.getPosition()+","+mapPoi.getUid() );//經度
                LatLng latLng = mapPoi.getPosition();
                setMarkPoint(latLng.latitude,latLng.longitude);
                mLatitude = latLng.latitude;
                mLongitude = latLng.longitude;
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.type_normal:
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                break;
            case R.id.type_satellite:
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.map_position:
                mLocClient.start();
                break;
            case R.id.confirm:
                Intent intent = new Intent();
                intent.putExtra("latitude", mLatitude);
                intent.putExtra("longitude", mLongitude);
                intent.putExtra("address", mAddress);
                Log.d("flag", "onClick: "+mLatitude+":"+mLongitude+":"+mAddress);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }

    LatLng point;
    private void setMarkPoint(double jingdu,double weidu) {
        //定義Maker座標點
        mBaiduMap.clear();
        point = new LatLng(jingdu, weidu);
        //構建Marker圖標
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_gcoding);
        //構建MarkerOption,用於在地圖上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地圖上添加Marker,並顯示
        mBaiduMap.addOverlay(option);
    }

    GeoCoder mSearch;
    private void initSearch() {
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                Log.e(TAG, "onGetGeoCodeResult latitude: "+geoCodeResult.getLocation() );//經度
                LatLng latLng = geoCodeResult.getLocation();
                if (latLng != null) {
                    mLatitude = latLng.latitude;
                    mLongitude = latLng.longitude;
                }
                isFirstLoc = true;
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                Log.e(TAG, "onGetReverseGeoCodeResult latitude: "+reverseGeoCodeResult.getLocation() );//經度
            }
        });

        mSearch.geocode(new GeoCodeOption().city(mAddress).address(mAddress));
//        Address address = getGeoPointBystr(MapForOfficeActivity.this,mAddress);
//        Log.e(TAG, "initSearch latitude: "+address.getLatitude()+","+address.getLongitude() );//經度
//        mLatitude = address.getLatitude();
//        mLongitude = address.getLongitude();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity執行onResume時執行mMapView. onResume (),實現地圖生命週期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity執行onPause時執行mMapView. onPause (),實現地圖生命週期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命週期管理
        mLocClient.stop();
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
    }
}

4. activity_map_for_office.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:background="@color/colorActionBar"
    android:clipToPadding="true"
    android:fitsSystemWindows="true"
    android:orientation="vertical"
    tools:context=".modules.office.MapForOfficeActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorTextWhite">

        <com.baidu.mapapi.map.MapView
            android:id="@+id/bmapView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true"
            android:focusable="true" />
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/type_normal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="地圖"
                android:textColor="@color/boxing_black" />

            <TextView
                android:id="@+id/type_satellite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="衛星"
                android:textColor="@color/boxing_black" />
        </LinearLayout>

        <TextView
            android:id="@+id/map_position"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="45dp"
            android:layout_marginStart="20dp"
            android:layout_marginTop="20dp"
            android:text="定位"
            android:textColor="@color/boxing_black" />
        <TextView
            android:background="@color/color_333333"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="@dimen/px10"
            android:layout_alignParentBottom="true"
            android:text="點擊單位所在位置獲取定位"
            android:textColor="@color/colorTextWhite" />

    </RelativeLayout>
</LinearLayout>

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章