Android 如何获取设备的当前位置?谷歌地图

Android 如何获取设备的当前位置?谷歌地图,android,google-maps,localization,geolocation,google-maps-android-api-2,Android,Google Maps,Localization,Geolocation,Google Maps Android Api 2,我需要知道当我点击地图时放置的标记的纬度和经度,我还需要知道如何实现,以便当我打开地图时,标记被放置在当前位置,我看到了许多视频和教程,但没有一个有效或过时等 有关守则: onCreate: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); m

我需要知道当我点击地图时放置的标记的纬度和经度,我还需要知道如何实现,以便当我打开地图时,标记被放置在当前位置,我看到了许多视频和教程,但没有一个有效或过时等

有关守则:

onCreate:

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);
    mPost = new Post();
    initPantallaAdd();
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());


    if(status == ConnectionResult.SUCCESS){
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapAddUbicacion);
        mapFragment.getMapAsync(this);



    }else{
        Toast.makeText(getApplicationContext(), "Please install google play services", Toast.LENGTH_SHORT).show();
    }

}       
  @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    UiSettings uiSettings = mMap.getUiSettings();
    uiSettings.setZoomControlsEnabled(true);


     LatLng sydney = new LatLng(-0.193805, -78.467102);
    CameraPosition cp = CameraPosition.builder().target(sydney).zoom(16).tilt(3).build();

    float zoomlevel = 16;

    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

            mMap.clear();
            MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)).title("Selected point");
            mMap.addMarker(markerOptions);

        }
    });
   }
onMapReady:

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);
    mPost = new Post();
    initPantallaAdd();
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());


    if(status == ConnectionResult.SUCCESS){
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapAddUbicacion);
        mapFragment.getMapAsync(this);



    }else{
        Toast.makeText(getApplicationContext(), "Please install google play services", Toast.LENGTH_SHORT).show();
    }

}       
  @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    UiSettings uiSettings = mMap.getUiSettings();
    uiSettings.setZoomControlsEnabled(true);


     LatLng sydney = new LatLng(-0.193805, -78.467102);
    CameraPosition cp = CameraPosition.builder().target(sydney).zoom(16).tilt(3).build();

    float zoomlevel = 16;

    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

            mMap.clear();
            MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)).title("Selected point");
            mMap.addMarker(markerOptions);

        }
    });
   }
我实现了这些方法,但我不知道该怎么做:

  //==============================================================================================
// ON CONNECTION CALLBACKS
@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

//==============================================================================================
// LOCATION LISTENER

@Override
public void onLocationChanged(Location location) {

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

需要GPS服务来获取当前位置的纬度和经度

Android定位API将为您提供融合定位功能。检查以下链接以更好地理解


  • 查看此代码以获取当前的纬度和经度

     public class MerchantTrack extends Common implements 
     GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {
    
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.merchant_track);
        backbuttn=(ImageView)findViewById(R.id.backbuttn);
        getSupportActionBar().hide();
    
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();
        connectClient();
    
    
    
    }
    
    
    protected void connectClient() {
        // Connect the client.
        if (isGooglePlayServicesAvailable() && mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }
    
    private boolean isGooglePlayServicesAvailable() {
        // Check that Google Play services is available
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            // In debug mode, log the status
            Log.d("Location Updates", "Google Play services is available.");
            return true;
        } else {
            // Get the error dialog from Google Play services
            Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
    
            // If Google Play services can provide an error dialog
            if (errorDialog != null) {
                // Create a new DialogFragment for the error dialog
                UberMapsActivity.ErrorDialogFragment errorFragment = new UberMapsActivity.ErrorDialogFragment();
                errorFragment.setDialog(errorDialog);
                errorFragment.show(getSupportFragmentManager(), "Location Updates");
            }
    
            return false;
        }
    }
    
    
    
    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location != null) {
    
            //Toast.makeText(this, "GPS location was found!", Toast.LENGTH_SHORT).show();
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            latitudE = location.getLatitude();
            longitudE = location.getLongitude();
    
            Log.d("locationnss", String.valueOf(latitudE));
    
    
            new MerchLocAsync().execute();
    
        } else {
            new AlertDialog.Builder(MerchantTrack.this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setMessage("Current location is unavailable!")
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
        startLocationUpdates();
    }
    
    protected void startLocationUpdates() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
    }
    
    
    @Override
    public void onConnectionSuspended(int i) {
    
    }
    
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    
    }
    
    @Override
    public void onLocationChanged(Location location) {
    
    }
    
    
    
    
    @Override
    public void onBackPressed() {
        Intent home = new Intent(MerchantTrack.this,Home.class);
        startActivity(home);
        super.onBackPressed();
    }
    

    要使用map,您必须按照以下步骤进行配置

    1-在google开发者控制台创建一个项目

    2-选择项目,左侧菜单将显示凭证选项单击它,然后您将获得选项创建凭证单击它,然后它将要求创建api密钥单击并创建我们的项目api密钥。

    3单击仪表板并选择屏幕顶部的项目,您将获得启用api的选项。

    4-在这里,您将看到许多谷歌api,在谷歌地图api部分,选择谷歌地图api android并单击启用。

    现在,您将获得一个可工作的api密钥此api密钥用于与map一起工作,这里我将为您提供我的存储库,您可以从中获取示例。您不需要配置api密钥,因为我正在其中使用api密钥。
    如果您想使用自己的api密钥,那么只需要更新manifiest文件元数据标记内项目中的api密钥

    首先将此权限添加到清单中

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
    对于Android N+,您需要在运行时检查权限在onCreate中检查此项:

       private LatLng start = null; //currentLocation
       GPSTracker gpsTracker;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
    
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    
            LocationListener mLocationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
    
                    start = new LatLng(location.getLatitude(), location.getLongitude());
                }
    
                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
    
                }
    
                @Override
                public void onProviderEnabled(String provider) {
    
                }
    
                @Override
                public void onProviderDisabled(String provider) {
    
                }
            };
    
    
            LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,
                        10, mLocationListener);
            }
    
    
        }
    
    并在onResume中检查是否授予了权限:

     @Override
    protected void onResume() {
        super.onResume();
    
        if (checkLocationPermission()) {
            gpsTracker = new GPSTracker(this);
            if (gpsTracker.canGetLocation) {
                start = new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude());
            } else {
                Toast.makeText(this, "please accept permission !!!!", Toast.LENGTH_SHORT).show();
                finish();
            }
    
        }
    }
    
    检查权限方法:

    public boolean checkLocationPermission() {
        String permission = "android.permission.ACCESS_FINE_LOCATION";
        int res = this.checkCallingOrSelfPermission(permission);
        return (res == PackageManager.PERMISSION_GRANTED);
    }
    
    最后在onRequestPermissionsResult中:

      @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    //Permission Granted 
    
                    gpsTracker = new GPSTracker(this);
                    if (gpsTracker.canGetLocation) {
                        start = new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude());
                    } else {
                        // permission denied, boo! Disable the
                        // functionality that depends on this permission.
                    }
                    return;
                }
                // other 'case' lines to check for other
                // permissions this app might request
            }
        }
    }
    
    现在start是设备的当前位置,并在位置更改时更新

    注意:如果用户拒绝权限活动未启动(finish()),请在需要其他操作时更改它

    通过这种方法,你不需要GMap就能获得位置,并且可以手动在地图上显示这个位置


    我希望有用:)

    谢谢我会看到的第一个链接是不完整的教程LocationServices.API,没有发现必须使用此库-编译'com.google.android.gms:play services:6.5.87'我在firebase中使用10.0.2,这不会导致异常?