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

时间:2017-04-29 06:06:50

标签: 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);
    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();
    }

}       

onMapReady:

  @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) {

}

4 个答案:

答案 0 :(得分:2)

首先将此权限添加到清单

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

将此类用于Handle GpsTrack:

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    public boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message_Preview
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message_Preview
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

对于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
        }
    }
}

现在开始是设备的当前位置,并在位置更改时更新!

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

通过这种方法,您可以获得位置而无需GMap,并且可以在地图上手动显示此latlng。

我希望有用:)

答案 1 :(得分:1)

要使用地图,您必须按照一些步骤进行配置。

1-在google开发者控制台创建项目。 https://console.developers.google.com/

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

点击信息中心并点击屏幕顶部的项目,您将获得启用api的选项。

4-在这里你会有很多谷歌api,在谷歌地图api部分选择谷歌地图api android并点击启用。

现在你将获得一个工作的api密钥这个api密钥用于处理map 这里我给你的存储库你可以从中获取示例。你不需要为api键配置我正在使用我的api密钥。               如果你想使用你自己的api密钥,你只需要更新项目中最明显的文件元数据标签中的api密钥。 here is a working example

答案 2 :(得分:0)

需要GPS服务才能获得当前位置的纬度和经度。

Android位置API 将为您提供融合的位置功能。请查看以下链接以便更好地理解。

  1. http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
  2. http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/

答案 3 :(得分:0)

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

 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();
}