GPS定位与高德地图的使用

本文介绍了Android平台下GPS定位的三种方式:GPS定位、Network定位(包括基站定位和WIFI定位)、AGPS定位,分析了各自的优缺点。接着详细讲解了如何在Android应用中实现GPS定位的代码,并添加了高德地图SDK的依赖,提供了XML布局和Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.GPS定位:android 的三种定位方式

1.GPS定位:需要GPS硬件支持,直接和卫星交互来获取当前经纬度。
  优点:速度快、精度高、可在无网络情况下使用。
  缺点:首次连接时间长、只能在户外已经开阔地使用,设备上方有遮挡物就不行了、比较耗电。
2.Network定位:又细分为WIFI定位和基站定位
(1)基站定位:一般手机附近的三个基站进行三角定位,由于每个基站的位置是固定的,利用电磁波在这三个基站间中转所需要时间来算出手机所在的坐标
a.优点:受环境的影响情况较小,不管在室内还是人烟稀少的地方都能用,只要有基站。
b.缺点:首先需要消耗流量、其实精度没有GPS那么准确,大概在十几米到几十米之间
(2)WIFI定位:
a.优点:和基站定位一样,它的优势在于收环境影响较小,只要有Wifi的地方可以使用。
b.缺点:需要有wifi、精度不准
3.AGPS定位:AssistedGPS(辅助全球卫星定位系统),是结合GSM或GPRS与传统卫星定位

2.GPS定位代码

清单文件权限

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

代码


public class MainActivity extends AppCompatActivity {
    LocationManager manager;
    String[] permissions;

    boolean hasnoPermission=false;
    boolean isOk=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //要申请的权限列表
        permissions=new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION};

        manager = (LocationManager) getSystemService(LOCATION_SERVICE);//获得定位的管理类
        initPermission();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

    }



    public void initPermission(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            for(String per: permissions){
                if(checkSelfPermission(per)!=PackageManager.PERMISSION_GRANTED){
                    hasnoPermission=true;
                    break;
                }
            }
            if(hasnoPermission){
               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 resule:grantResults){
                        if(resule!=PackageManager.PERMISSION_GRANTED){
                            isOk=true;
                            break;
                }
            }
            if(isOk){
                Log.d("aaaa", "onRequestPermissionsResult: 权限没有申请成功");
            }
        }


    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Log.d("aaaa", "onLocationChanged: 经度"+location.getLatitude());
            Log.d("aaaa", "onLocationChanged: 纬度"+location.getLongitude());
            Log.d("aaaa", "onLocationChanged: 海拔"+location.getAltitude());

        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
}


使用高德地图

添加依赖:implementation ‘com.amap.api:map2d:5.2.0’

xml布局

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</LinearLayout>

Java代码

public class Main2Activity extends AppCompatActivity implements AMapLocationListener , LocationSource {

    TextView mLocation;

    MapView mapView;
    AMap aMap;
    OnLocationChangedListener mListener;
    AMapLocationClient client;
    AMapLocationClientOption op;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        checkPermisson();

        mapView=findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        if(aMap==null){
            aMap=mapView.getMap();
            init();
        }




    }

    private void init() {
        MyLocationStyle myLocationStyle=new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher_round));
        myLocationStyle.radiusFillColor(Color.argb(100,0,0,180));
        myLocationStyle.strokeWidth(1.0f);
        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();







    }

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


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

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

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

    }



    @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)
             mListener.onLocationChanged(aMapLocation);

    }

    String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void checkPermisson(){
        boolean flag=true;//默认全部被申请过
        for(int i=0;i<permissions.length;i++){//只要有一个没有申请成功
            if(!(ActivityCompat.checkSelfPermission(this,permissions[i])== PackageManager.PERMISSION_GRANTED)){
                flag=false;
            }
        }
        if(!flag){
            //动态申请权限
            requestPermissions(permissions,100);
        }
    }




    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

        mListener=onLocationChangedListener;
        if(client==null){
             client=new AMapLocationClient(getApplicationContext());
             op=new AMapLocationClientOption();
             client.setLocationListener(this);
             op.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
             client.setLocationOption(op);
             client.startLocation();

        }

    }

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

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==100){
            boolean flag=true;
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i]!=PackageManager.PERMISSION_GRANTED){
                    flag=false;
                }
            }
            if(flag){
                Toast.makeText(this, "ok ", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
            }
        }


    }
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值