1. 程式人生 > >高德地圖定位(簡易版)

高德地圖定位(簡易版)

首先要有在官網下載的demo
首先導依賴
在這裡插入圖片描述
在當前module 中的build.grade 中新增
在這裡插入圖片描述

sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }

建立一個 名為 LocationUtil的類直接複製裡面的程式碼

public class LocationUtil implements AMapLocationListener {
    private AMapLocationClient aMapLocationClient;
    private AMapLocationClientOption clientOption;
    private ILocationCallBack callBack;

    public void startLocate(Context context){
        aMapLocationClient = new AMapLocationClient(context);

        //設定監聽回撥
        aMapLocationClient.setLocationListener(this);

        //初始化定位引數
        clientOption = new AMapLocationClientOption();
        clientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        clientOption.setNeedAddress(true);
        clientOption.setOnceLocation(false);
        //設定是否強制重新整理WIFI,預設為強制重新整理
        clientOption.setWifiActiveScan(true);
        //設定是否允許模擬位置,預設為false,不允許模擬位置
        clientOption.setMockEnable(false);
        //設定定位間隔
        clientOption.setInterval(2000);
        aMapLocationClient.setLocationOption(clientOption);

        aMapLocationClient.startLocation();
    }

    //完成定位回撥
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if(aMapLocation != null){
            if(aMapLocation.getErrorCode() == 0){
                //定位成功完成回撥
                String country = aMapLocation.getCountry();
                String province = aMapLocation.getProvince();
                String city = aMapLocation.getCity();
                String district = aMapLocation.getDistrict();
                String street = aMapLocation.getStreet();
                double lat = aMapLocation.getLatitude();
                double lgt = aMapLocation.getLongitude();

                callBack.callBack(country + province + city + district + street,lat,lgt,aMapLocation);
            }else{
                //顯示錯誤資訊ErrCode是錯誤碼,errInfo是錯誤資訊,詳見錯誤碼錶。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }

    /**
     * 自定義圖示
     * @return
     */
    public MarkerOptions getMarkerOption(String str, double lat, double lgt){
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher));
        markerOptions.position(new LatLng(lat,lgt));
        markerOptions.title(str);
        markerOptions.snippet("緯度:" + lat + "   經度:" + lgt);
        markerOptions.period(100);

        return markerOptions;
    }

    public interface ILocationCallBack{
        void callBack(String str,double lat,double lgt,AMapLocation aMapLocation);
    }

    public void setLocationCallBack(ILocationCallBack callBack){
        this.callBack = callBack;
    }
}

複製MainActivity 中的程式碼

public class MainActivity extends AppCompatActivity implements LocationSource{

    private MapView mapView;
    private AMap aMap;
    private LocationSource.OnLocationChangedListener mListener = null;//定位監聽器
    private LocationUtil locationUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mapView = (MapView) findViewById(R.id.MapView);
        mapView.onCreate(savedInstanceState);

        init();
    }

    private void init() {
        if(aMap == null){
            aMap = mapView.getMap();
        }

        setLocationCallBack();

        //設定定位監聽
        aMap.setLocationSource(this);
        //設定縮放級別
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        //顯示定位層並可觸發,預設false
        aMap.setMyLocationEnabled(true);
    }

    private void setLocationCallBack(){
        locationUtil = new LocationUtil();
        locationUtil.setLocationCallBack(new LocationUtil.ILocationCallBack() {
            @Override
            public void callBack(String str,double lat,double lgt,AMapLocation aMapLocation) {

                //根據獲取的經緯度,將地圖移動到定位位置
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(lat,lgt)));
                mListener.onLocationChanged(aMapLocation);
                //新增定點陣圖標
                aMap.addMarker(locationUtil.getMarkerOption(str,lat,lgt));
            }
        });
    }

    //定位啟用回撥
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;

        locationUtil.startLocate(getApplicationContext());
    }

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

    @Override
    protected void onPause() {
        super.onPause();
        //暫停地圖的繪製
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //銷燬地圖
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //重新繪製載入地圖
        mapView.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
}

activity_main 中的程式碼

    <com.amap.api.maps.MapView
        android:id="@+id/MapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></com.amap.api.maps.MapView>

在清單檔案中新增的許可權

<!-- Normal Permissions 不需要執行時註冊 -->
    <!-- 獲取運營商資訊,用於支援提供運營商資訊相關的介面 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- 用於訪問wifi網路資訊,wifi資訊會用於進行網路定位 -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- 這個許可權用於獲取wifi的獲取許可權,wifi資訊會用來進行網路定位 -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission
        android:name="android.permission.CHANGE_CONFIGURATION"
        tools:ignore="ProtectedPermissions" />

    <!-- 請求網路 -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- 不是SDK需要的許可權,是示例中的後臺喚醒定位需要的許可權 -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <!-- 需要執行時註冊的許可權 -->
    <!-- 用於進行網路定位 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 用於訪問GPS定位 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- 用於提高GPS定位速度 -->
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <!-- 寫入擴充套件儲存,向擴充套件卡寫入資料,用於寫入快取定位資料 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 讀取快取資料 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <!-- 用於讀取手機當前的狀態 -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <!-- 更改設定 -->
    <uses-permission
        android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions" />

    <!-- 3.2.0版本增加 -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <!-- 3.2.0版本增加 -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <!--不用複製application中的本來就有的程式碼  -->
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- 設定key -->
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="xxxxxx" />
        <!-- 定位需要的服務 -->
        <service android:name="com.amap.api.location.APSService"></service>
    </application>

效果就出來了
在這裡插入圖片描述
如果沒有小三角的話就開啟一下 GPS 然後執行