Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 百度地圖檢索、定位

百度地圖檢索、定位

編輯:關於Android編程

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;

import java.util.List;

public class Baidumap extends AppCompatActivity {
    private BaiduMap mBaiduMap;
    MapView mMapView = null;
    boolean isFirstLoc = true; // 是否首次定位
    // 定位相關0p
    LocationClient mLocClient;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    private RoutePlanSearch mSearch;
    boolean useDefaultIcon = false;
    private Button btn1;
    private String name;
    private String adr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //在使用SDK各組件之前初始化context信息,傳入ApplicationContext
        //注意該方法要再setContentView方法之前實現
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_baidumap);
        Intent intent=getIntent();
        adr = intent.getStringExtra("adr");
        //獲取地圖控件引用
        btn1= (Button) findViewById(R.id.btn1);
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();

    //普通地圖
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mLocationClient = new LocationClient(getApplicationContext());     //聲明LocationClient類
        mLocationClient.registerLocationListener( myListener );    //注冊監聽函數
        initLocation();

        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(listener);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PlanNode stNode = PlanNode.withCityNameAndPlaceName("北京", name);
                PlanNode enNode = PlanNode.withCityNameAndPlaceName("北京", adr);
                mSearch.transitSearch((new TransitRoutePlanOption())
                        .from(stNode)
                        .city("北京")
                        .to(enNode));
            }
        });




    }
    OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
        public void onGetWalkingRouteResult(WalkingRouteResult result) {
            //
        }
        public void onGetTransitRouteResult(TransitRouteResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                Toast.makeText(Baidumap.this, "抱歉,未找到結果", Toast.LENGTH_SHORT).show();
            }
            if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                //起終點或途經點地址有岐義,通過以下接口獲取建議查詢信息
                //result.getSuggestAddrInfo()
                return;
            }
            if (result.error == SearchResult.ERRORNO.NO_ERROR) {

                TransitRouteOverlay overlay = new MyTransitRouteOverlay(mBaiduMap);
                mBaiduMap.setOnMarkerClickListener(overlay);
                overlay.setData(result.getRouteLines().get(0));
                overlay.addToMap();
                overlay.zoomToSpan();
            }
        }
        public void onGetDrivingRouteResult(DrivingRouteResult result) {
            //
        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

        }
    };
    private class MyTransitRouteOverlay extends TransitRouteOverlay {

        public MyTransitRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
            }
            return null;
        }
    }
    public void onReceivePoi(BDLocation poiLocation) {
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
            //在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命周期管理
            mMapView.onDestroy();
            // 退出時銷毀定位
            mLocClient.stop();
            // 關閉定位圖層
            mBaiduMap.setMyLocationEnabled(false);
            //在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命周期管理
            mMapView.onDestroy();
            mMapView=null;
        }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity執行onResume時執行mMapView. onResume (),實現地圖生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity執行onPause時執行mMapView. onPause (),實現地圖生命周期管理
        mMapView.onPause();
    }
    //地圖標注
    public void getLatLag(Double x ,Double y){
        //定義Maker坐標點
        LatLng point = new LatLng(x, y);
//構建Marker圖標
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_marka);
//構建MarkerOption,用於在地圖上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap)
                .zIndex(9)  //設置marker所在層級
                .draggable(true);  //設置手勢拖拽

        //在地圖上添加Marker,並顯示
        Marker marker = (Marker) mBaiduMap.addOverlay(option);

    }


    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可選,默認高精度,設置定位模式,高精度,低功耗,僅設備
        option.setCoorType("bd09ll");//可選,默認gcj02,設置返回的定位結果坐標系
        int span=0;
        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);
        mLocationClient.start();
    }
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
//Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位結果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 單位:公裡每小時
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 單位:米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 單位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 網絡定位結果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //運營商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("網絡定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 離線定位結果
                sb.append("\ndescribe : ");
                sb.append("離線定位成功,離線定位結果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服務端網絡定位失敗,可以反饋IMEI號和大體定位時間到[email protected],會有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("網絡不同導致定位失敗,請檢查網絡是否通暢");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("無法獲取有效定位依據導致定位失敗,一般是由於手機的原因,處於飛行模式下一般會造成這種結果,可以試著重啟手機");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置語義化信息
            List list = location.getPoiList();// POI數據
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());
            getLatLag(location.getLatitude(),location.getLongitude());
            name=list.get(0).getName();
        }


    }

}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved