简单实现GPS定位

一、权限添加:

	
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

二、GPS常用类:

LocationManager:位置信息管理类:
Android为定位系统提供了LocationManager管理类。通过LocationManager和其他几个辅助类,开发人员可以方便开发出GPS应用。

LocationProvider:提供定位信息的类:
LocationManager 提供了方法getAllProviders()获取所有的LocationProvider;
也可以通过名称获取指定的LocationProvider。
(1) GPS定位:通过卫星实现的
LocationProvider lProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER);
(2) 网络定位:通过WI-FI 或者信号塔进行定位
LocationProviderlProvider=locationManager.getProvider(LocationManager.NETWORK_PROVIDER);

Location:位置类:
double getLatiude() 获取纬度位置;
double getLongtitude() 获取经度值;
double getAltitude() 获取海拔;

三、java代码:

package com.example.day09;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.MyLocationStyle;

public class day09 extends AppCompatActivity implements AMapLocationListener, LocationSource {
    LocationManager locationManager;
    private AMapLocationClientOption op;//参数设置
    private AMapLocationClient client;//定位客户端
    //要申请的权限列表
    String permissions[] = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE};
    boolean isOk = false;
    boolean noPermission = false;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_day09);
        mapView = findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        if(aMap == null){
            aMap = mapView.getMap();
        }
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);//获得定位管理类
        initPermission();

        initDot();
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        /**
         * 第一个参数:位置提供器的类型
         * 第二个参数:监听位置变化的时间间隔,毫秒为单位
         * 第三个参数:监听位置变化的距离间隔,米为单位
         * 第四个参数:LocationListener监听器
         */
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.e("#精度是:", location.getLatitude() + "");
                Log.e("#纬度是:", location.getLongitude() + "");
                Log.e("#海拔是:", location.getAltitude() + "");
            }

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

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        });

    }
    private void initLocation() {
        client = new AMapLocationClient(getApplicationContext());
        op = new AMapLocationClientOption();
        //设置定位回到监听
        client.setLocationListener(this);
        //配置定位参数
        op.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        op.setInterval(1000);//每隔一秒定位一次
        op.setNeedAddress(true);//是否需要返回地点
        op.setMockEnable(true);//是否虚拟定位
        client.setLocationOption(op);
        client.startLocation();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void initPermission(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            for(String per:permissions){
                if(checkSelfPermission(per)!= PackageManager.PERMISSION_GRANTED){
                    noPermission = true;
                    break;
                }
            }
        }
        if(noPermission){
            //去申请权限
            requestPermissions(permissions,100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100){
            for (int i = 0;i < grantResults.length;i++){
                if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    isOk = true;
                    break;
                }
            }
            if(isOk){
                Log.e("error###","没有成功!!!!");
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.e("ZXY","errorCode:"+aMapLocation.getErrorCode());
        Log.e("ZXY","errorInfo:"+aMapLocation.getErrorInfo());
        Log.e("ZXY","地址:"+aMapLocation.getAddress());
        Log.e("ZXY","纬度:"+aMapLocation.getLatitude());
        Log.e("ZXY","经度:"+aMapLocation.getLongitude());
    }
}

效果:

简单实现GPS定位_第1张图片

GPS与谷歌地图的使用:

依赖:
implementation ‘com.amap.api:location:4.2.0’
implementation’com.amap.api:map2d:5.2.0’

布局代码:


<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=".day09">

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

    com.amap.api.maps2d.MapView>

RelativeLayout>

java代码:

package com.example.day09;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.MyLocationStyle;

public class day09 extends AppCompatActivity implements AMapLocationListener, LocationSource {
    LocationManager locationManager;
    private AMapLocationClientOption op;//参数设置
    private AMapLocationClient client;//定位客户端
    private OnLocationChangedListener onLocationChangedListener;
    private MapView mapView;
    private AMap aMap;
    //要申请的权限列表
    String permissions[] = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE};
    boolean isOk = false;
    boolean noPermission = false;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_day09);
        mapView = findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        if(aMap == null){
            aMap = mapView.getMap();
        }
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);//获得定位管理类
        initPermission();

        initDot();
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        /**
         * 第一个参数:位置提供器的类型
         * 第二个参数:监听位置变化的时间间隔,毫秒为单位
         * 第三个参数:监听位置变化的距离间隔,米为单位
         * 第四个参数:LocationListener监听器
         */
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.e("#精度是:", location.getLatitude() + "");
                Log.e("#纬度是:", location.getLongitude() + "");
                Log.e("#海拔是:", location.getAltitude() + "");
            }

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

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        });

    }

    private void initDot() {
        //自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher_round));//设置图标
        myLocationStyle.strokeColor(Color.BLUE);//设置 圆形外边框
        myLocationStyle.radiusFillColor(Color.argb(100,0,0,100));//设置圆形的填充色
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);
        aMap.setMyLocationEnabled(true);
    }

    private void initLocation() {
        client = new AMapLocationClient(getApplicationContext());
        op = new AMapLocationClientOption();
        //设置定位回到监听
        client.setLocationListener(this);
        //配置定位参数
        op.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        op.setInterval(1000);//每隔一秒定位一次
        op.setNeedAddress(true);//是否需要返回地点
        op.setMockEnable(true);//是否虚拟定位
        client.setLocationOption(op);
        client.startLocation();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void initPermission(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            for(String per:permissions){
                if(checkSelfPermission(per)!= PackageManager.PERMISSION_GRANTED){
                    noPermission = true;
                    break;
                }
            }
        }
        if(noPermission){
            //去申请权限
            requestPermissions(permissions,100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100){
            for (int i = 0;i < grantResults.length;i++){
                if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    isOk = true;
                    break;
                }
            }
            if(isOk){
                Log.e("error###","没有成功!!!!");
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.e("ZXY","errorCode:"+aMapLocation.getErrorCode());
        Log.e("ZXY","errorInfo:"+aMapLocation.getErrorInfo());
        Log.e("ZXY","地址:"+aMapLocation.getAddress());
        Log.e("ZXY","纬度:"+aMapLocation.getLatitude());
        Log.e("ZXY","经度:"+aMapLocation.getLongitude());

        //显示系统小蓝点
        if(aMapLocation.getErrorCode() == 0){
            onLocationChangedListener.onLocationChanged(aMapLocation);//显示系统小蓝点
        }

        Toast.makeText(this, "定位地址:"+aMapLocation.getAddress(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        this.onLocationChangedListener = onLocationChangedListener;
        if (client == null){
            initLocation();
        }
    }

    @Override
    public void deactivate() {
        onLocationChangedListener = null;
        if(onLocationChangedListener != null){
            client.stopLocation();
            client.onDestroy();
        }
        client = null;
    }

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

效果图:

简单实现GPS定位_第2张图片

你可能感兴趣的:(简单实现GPS定位)