GPS定位+经纬度定位

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

2、权限+key:

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

key放自己的!!!

    <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" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />

3、简单的xml布局

扫描二维码关注公众号,回复: 11929831 查看本文章
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.dyw.testgps.TestLocation">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
        <TextView
            android:text="经度"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/lng"
            android:layout_width="85dp"
            android:layout_height="wrap_content"
            android:text="118.899714"
            android:inputType="numberDecimal"/>
        <TextView
            android:text="纬度"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/lat"
            android:layout_width="85dp"
            android:layout_height="wrap_content"
            android:text="31.90397"
            android:inputType="numberDecimal"/>
        <Button
            android:id="@+id/loc"
            android:text="定位"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"/>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
        <RadioGroup
            android:id="@+id/rg"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
        <RadioButton
            android:id="@+id/manual"
            android:text="手动定位"
            android:checked="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <RadioButton
            android:id="@+id/gps"
            android:text="GPS定位"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        </RadioGroup>
    </LinearLayout>
    <com.amap.api.maps.MapView
        android:id="@+id/map1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.amap.api.maps.MapView>
</LinearLayout>


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<BitmapDescriptor> 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<MarkerOptions> 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 {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
            }
        }
    }
}

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

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

猜你喜欢

转载自blog.csdn.net/qq_28190653/article/details/73278207
今日推荐