GPS定位+经纬度定位

1、从高德地图下载sdk并放入相应的包

GPS定位+经纬度定位_第1张图片

GPS定位+经纬度定位_第2张图片

2、权限+key:

 

key放自己的!!!

 

 

    
    
    
    
    
    
    
    
    
    

 

3、简单的xml布局

 



    
        
        
        
        
        


4、Java:

 

 

public class TestLocation extends AppCompatActivity {
    private MapView mapView;
    private AMap aMap;
    private LocationManager locationManager;
    String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_location);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mapView = (MapView) findViewById(R.id.map1);
        mapView.onCreate(savedInstanceState);
        init1();
        RadioButton rb = (RadioButton) findViewById(R.id.gps);
        rb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (Build.VERSION.SDK_INT > 23) {
                        if (!checkPermissionAllGranted(permission)) {
                            requestPermissions(permission, 10000);
                        } else {
                            Log.d("----GPS----", "使用GPS");
                            getGPS();
                        }
                    } else {
                        Log.d("----GPS----", "使用GPS");
                        getGPS();
                    }
                }
            }
        });
        Button bn = (Button) findViewById(R.id.loc);
        final TextView latTv = (TextView) findViewById(R.id.lat);
        final TextView lngTv = (TextView) findViewById(R.id.lng);
        bn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String lng = lngTv.getEditableText().toString().trim();
                String lat = latTv.getEditableText().toString().trim();
                if (lng.equals("") || lat.equals("")) {
                    Toast.makeText(TestLocation.this, "请输入有效的经度、纬度", Toast.LENGTH_SHORT).show();
                } else {
                    ((RadioButton) findViewById(R.id.manual)).setChecked(true);
                    double dlng = Double.parseDouble(lng);
                    double dlat = Double.parseDouble(lat);
                    Log.d("----经度----", dlng + "");
                    Log.d("----纬度----", dlat + "");
                    LatLng pos = tra(dlat, dlng);
                    Log.d("------pos------", pos + "");
                    CameraUpdate cu = CameraUpdateFactory.changeLatLng(pos);
                    aMap.moveCamera(cu);
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(pos);
                    markerOptions.title("金陵科技学院");
                    markerOptions.snippet("摘录信息:教育");
                    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    markerOptions.draggable(true);
                    Marker marker = aMap.addMarker(markerOptions);
                    marker.showInfoWindow();
                    MarkerOptions markerOptions1 = new MarkerOptions();
                    LatLng pos1 = tra(dlat + 0.001, dlng);
                    Log.d("dasdadasdadas", pos1 + "");
                    markerOptions1.position(pos1)
                            .title("金陵科技学院食堂")
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
                            .draggable(true);
                    ArrayList giflist = new ArrayList<>();
                    giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                    giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                    giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
                    LatLng pos2 = tra(dlat - 0.001, dlng);
                    MarkerOptions markerOptions2 = new MarkerOptions()
                            .position(pos2)
                            .icons(giflist)
                            .title("金陵科技学院宿舍")
                            .draggable(true)
                            .period(10);
                    ArrayList optionlist = new ArrayList<>();
                    optionlist.add(markerOptions1);
                    optionlist.add(markerOptions2);
                    aMap.addMarkers(optionlist, true);
                }
            }
        });
    }

    private void getGPS() {
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300, 8, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updatePosition(location);
                double latt = location.getLatitude();
                double lngg = location.getLongitude();
                Log.d("----latt-----", latt + "+++++++");
                Log.d("----lngg-----", lngg + "+++++++");

            }

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

            @Override
            public void onProviderEnabled(String provider) {
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                updatePosition(locationManager.getLastKnownLocation(provider));
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        });
    }
    private LatLng tra(double i, double j){
        LatLng gps = new LatLng(i, j);
        CoordinateConverter converter = new CoordinateConverter(this);
        converter.from(CoordinateConverter.CoordType.GPS);
        converter.coord(gps);
        LatLng pos = converter.convert();
        return pos;
    }

    private void updatePosition(Location location) {
        LatLng gps = new LatLng(location.getLatitude(), location.getLongitude());
        CoordinateConverter converter = new CoordinateConverter(this);
        converter.from(CoordinateConverter.CoordType.GPS);
        converter.coord(gps);
        LatLng pos = converter.convert();
        CameraUpdate cu = CameraUpdateFactory.changeLatLng(pos);
        aMap.moveCamera(cu);
        aMap.clear();
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(pos);

        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher_round));
        markerOptions.draggable(true);
        Log.d("----updateposition----", "pos:" + pos);
        Marker marker = aMap.addMarker(markerOptions);
        Log.d("----updateposition----", "marker:" + marker);
    }

    private void init1() {
        if (aMap == null) {
            aMap = mapView.getMap();
            CameraUpdate cu = CameraUpdateFactory.zoomTo(15);
            aMap.moveCamera(cu);
            CameraUpdate tiltUpdate = CameraUpdateFactory.changeTilt(30);
            aMap.moveCamera(tiltUpdate);
        }
    }

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

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

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

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

    }

    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                return false;
            }
        }
        return true;
  }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 10000) {
            boolean isAllGranted = true;

            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                // 如果所有的权限都授予了, 则执行备份代码
                Log.d("GPS","执行");
                getGPS();
            } else {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
            }
        }
    }
}

有问题,请多指教!!!!

关注我的技术公众号,每个工作日都有优质技术文章推送。
微信扫一扫下方二维码即可关注:

GPS定位+经纬度定位_第3张图片

你可能感兴趣的:(Android)