1. 程式人生 > >快速簡單高德地圖接入

快速簡單高德地圖接入

1.匯入SDK

連結:https://pan.baidu.com/s/1vdoPXmsZ4CuVfV_J144zuw 密碼:fvv2

裡面有定位 地圖  獲取螢幕中心經緯度 距離測量

用的是EventBus傳值

2.新增許可權

<!-- 用於訪問網路,網路定位需要上網 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 寫入擴充套件儲存,向擴充套件卡寫入資料,用於寫入快取定位資料 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 用於進行網路定位 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 獲取運營商資訊,用於支援提供運營商資訊相關的介面 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- 用於訪問GPS定位 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- 用於讀取手機當前的狀態 -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- 用於訪問wifi網路資訊,wifi資訊會用於進行網路定位 -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- 這個許可權用於獲取wifi的獲取許可權,wifi資訊會用來進行網路定位 -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!-- 這個許可權用於允許程式在手機螢幕關閉後後臺程序仍然執行 -->
    <user-permission android:name="android.permission.WAKE_LOCK" />

3.加入你的application裡面

<meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="你的key" />

        <service android:name="com.amap.api.location.APSService" />

4.到EventBus包

implementation 'de.greenrobot:eventbus:3.0.0-beta1'

5.主函式

public class MapActivity extends BaseActivity implements
        GeocodeSearch.OnGeocodeSearchListener,
        AMap.OnCameraChangeListener,
        DistanceSearch.OnDistanceSearchListener, LocationSource {


    private MapView mapView;
    private AMap aMap;
    private boolean tag=false;
    private GeocodeSearch geocodeSearch;
    private OnLocationChangedListener mListener;
    private boolean isFirstLoc=false;

    private double latitu2,longitu2;
    public double latitu1=0.0;
    public double longitu1=0.0;
    private DistanceSearch distanceSearch;
    private DistanceSearch.DistanceQuery distanceQuery;

    //宣告AMapLocationClient類物件
    public AMapLocationClient mLocationClient = null;



    /**
     * 宣告定位回撥監聽器
     */
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回撥資訊,設定相關訊息
                    amapLocation.getLocationType();//獲取當前定位結果來源,如網路定位結果,詳見定位型別表
                    amapLocation.getLatitude();//獲取緯度
                    amapLocation.getLongitude();//獲取經度
                    amapLocation.getAccuracy();//獲取精度資訊
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);//定位時間
                    amapLocation.getAddress();//地址,如果option中設定isNeedAddress為false,則沒有此結果,網路定位結果中會有地址資訊,GPS定位不返回地址資訊。
                    amapLocation.getCountry();//國家資訊
                    amapLocation.getProvince();//省資訊
                    amapLocation.getCity();//城市資訊
                    amapLocation.getDistrict();//城區資訊
                    amapLocation.getStreet();//街道資訊
                    amapLocation.getStreetNum();//街道門牌號資訊
                    amapLocation.getCityCode();//城市編碼
                    amapLocation.getAdCode();//地區編碼
                    amapLocation.getAoiName();//獲取當前定位點的AOI資訊
                    lat = amapLocation.getLatitude();
                    lon = amapLocation.getLongitude();
                    Log.v("pcw", "lat : " + lat + " lon : " + lon);
                    Log.v("pcw", "Country : " + amapLocation.getCountry() + " province : " + amapLocation.getProvince() + " City : " + amapLocation.getCity() + " District : " + amapLocation.getDistrict());

                    // 設定當前地圖顯示為當前位置
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 15));
                    MarkerOptions markerOptions = new MarkerOptions();
                    aMap.addMarker(markerOptions);

                    // 如果不設定標誌位,此時再拖動地圖時,它會不斷將地圖移動到當前的位置
                    if (isFirstLoc==true) {
                        //設定縮放級別
                        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                        //將地圖移動到定位點
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
                        //點選定位按鈕 能夠將地圖的中心移動到定位點
                        mListener.onLocationChanged(amapLocation);
                        isFirstLoc = false;
                    }

                } else {
                    //顯示錯誤資訊ErrCode是錯誤碼,errInfo是錯誤資訊,詳見錯誤碼錶。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //宣告mLocationOption物件
    public AMapLocationClientOption mLocationOption = null;
    private double lat;
    private double lon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_activity);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);//必須要寫

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //設定定位回撥監聽
        mLocationClient.setLocationListener(mLocationListener);

        init();
        aMap.setOnCameraChangeListener(this);




    }


    /**
     * * 初始化AMap物件
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        //構造一個預設的位置
        LatLng latLng = new LatLng(latitu1,longitu1);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
        // 是否顯示定位按鈕
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
        //設定定位監聽
        aMap.setLocationSource(this);
        // 是否可觸發定位並顯示定位層
        aMap.setMyLocationEnabled(true);

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher));// 自定義定位藍點圖示*/
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 自定義精度範圍的圓形邊框顏色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));//圓圈的顏色,設為透明的時候就可以去掉園區區域了
        aMap.setMyLocationStyle(myLocationStyle);

        //地理搜尋類
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        setUpMap();

    }

    private void setUpMap() {
        //初始化定位引數
        mLocationOption = new AMapLocationClientOption();
        //設定定位模式為高精度模式,Battery_Saving為低功耗模式,Device_Sensors是僅裝置模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //設定是否返回地址資訊(預設返回地址資訊)
        mLocationOption.setNeedAddress(true);
        //設定是否只定位一次,預設為false
        mLocationOption.setOnceLocation(true);
        //設定是否強制重新整理WIFI,預設為強制重新整理
        mLocationOption.setWifiActiveScan(true);
        //設定是否允許模擬位置,預設為false,不允許模擬位置
        mLocationOption.setMockEnable(false);
        //設定定位間隔,單位毫秒,預設為2000ms
        mLocationOption.setInterval(2000);
        //給定位客戶端物件設定定位引數
        mLocationClient.setLocationOption(mLocationOption);
        //啟動定位
        mLocationClient.startLocation();
    }


    /**
     * 方法必須重寫
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必須重寫
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.stopLocation();//停止定位
        //關閉後臺定位,引數為true時會移除通知欄,為false時不會移除通知欄,但是可以手動移除
        if(android.os.Build.VERSION.SDK_INT >= 26){
            mLocationClient.disableBackgroundLocation(true);
        }

    }

    /**
     * 方法必須重寫
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必須重寫
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        mLocationClient.onDestroy();//銷燬定位客戶端。
    }
    public void affirm(View view){
         tag=true;
        //逆地理編碼
        getAddressByLatlng(new LatLng(latitu1,longitu1));
        getAddressByLatlng(new LatLng(latitu2,longitu2));
        chelian();
        Intent i=new Intent();
        setResult(0,i);
        finish();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
        ArrayList<String> arr = new ArrayList<>();
        if (tag == true) {
            arr.add(regeocodeAddress.getProvince());
            arr.add(regeocodeAddress.getCity());
            arr.add(regeocodeAddress.getDistrict());
            arr.add(regeocodeAddress.getTownship());
            arr.add(regeocodeAddress.getFormatAddress());
            arr.add(regeocodeAddress.getNeighborhood());
            EventBus.getDefault().post(arr);
        }

        Log.d("aaaaa", "onRegeocodeSearched: " + regeocodeAddress.getDistrict());
    }
    //////////////////////////////////////////////////
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        LatLng target = cameraPosition.target;
        if(latitu1==0.0){
            latitu1=target.latitude;
            longitu1=target.longitude;
        }
        latitu2=target.latitude;
        longitu2=target.longitude;
        Log.d("aaaaa", "onCameraChange111: "+target.latitude+"-----"+target.longitude);

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {

    }
    private void getAddressByLatlng(LatLng latLng) {
        //逆地理編碼查詢條件:逆地理編碼查詢的地理座標點、查詢範圍、座標型別。
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.GPS);
        //非同步查詢
        geocodeSearch.getFromLocationAsyn(query);
    }
    public void chelian(){
        distanceSearch = new DistanceSearch(this);
        distanceSearch.setDistanceSearchListener(this);
        distanceQuery = new DistanceSearch.DistanceQuery();
        LatLonPoint start = new LatLonPoint(latitu1, longitu1);
        LatLonPoint dest = new LatLonPoint(latitu2, longitu2);

        //設定起點和終點,其中起點支援多個
        List<LatLonPoint> latLonPoints = new ArrayList<LatLonPoint>();
        latLonPoints.add(start);
        distanceQuery.setOrigins(latLonPoints);
        distanceQuery.setDestination(dest);
        //設定測量方式,支援直線和駕車
        distanceQuery.setType(DistanceSearch.TYPE_DRIVING_DISTANCE);
        //請求經緯度的距離
        distanceSearch.calculateRouteDistanceAsyn(distanceQuery);
    }
    //得到距離   返回結果成功或者失敗的響應碼。1000為成功,其他為失敗
    @Override
    public void onDistanceSearched(DistanceResult result, int i) {
        if(i==1000){
            List<DistanceItem> distanceResults = result.getDistanceResults();
            for (int j = 0; j <distanceResults.size() ; j++) {
                Log.d("aaaaa", "onDistanceSearched: "+distanceResults.get(j).getDistance()+"米");
            }

        }
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        isFirstLoc=true;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }
}

7.主佈局

<RelativeLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".pub.MapActivity">
    <com.amap.api.maps.MapView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/coordicon"
        android:layout_centerInParent="true"/>
    <Button
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:text="@string/pub_but"
        android:textColor="@color/white"
        android:background="@drawable/usercenter_register_button"
        android:onClick="affirm"
        android:layout_marginBottom="7dp"
        />
</RelativeLayout>


8.副佈局

<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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="yizhong.com.xtzhangbinbin.jpq.app.Main2Activity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="bb"
        android:onClick="bb"/>
</LinearLayout>


9.如果你寫到這裡執行沒有實現定位成功的話   一定要注意你的包名


這裡的包名只能是下面圖的包名


下面我在送大家一個查詢SHA1的方法直接在你的專案中執行得到返回值就行了

//獲取SHA1安全碼
    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

直接在main函式中執行這個方法將返回值列印一下   複製到高德官網上就行了