【问题标题】:How to get the current location of the device? google maps如何获取设备的当前位置?谷歌地图
【发布时间】:2017-09-27 06:58:51
【问题描述】:

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

相关代码:

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

}

【问题讨论】:

    标签: android google-maps localization geolocation google-maps-android-api-2


    【解决方案1】:

    首先将此权限添加到清单

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

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

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

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

    希望对你有用:)

    【讨论】:

      【解决方案2】:

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

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

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

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

      4- 在这里你会看到很多google api,在google map api 部分选择google map api android 并点击启用。

      现在您将获得一个有效的 api 密钥,此 api 密钥用于与地图一起工作 这里我给您我的存储库,您可以从中获取示例。您不需要为 api 密钥配置我在其中使用我的 api 密钥。 如果您想使用自己的 api 密钥,您只需更新项目中清单文件元数据标记内的 api 密钥。 here is a working example

      【讨论】:

        【解决方案3】:

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

        Android Location 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/

        【讨论】:

        • 谢谢我会看到这个
        • 第一个链接不完整教程
        【解决方案4】:

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

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

        【讨论】:

        • LocationServices.API,没有找到
        • 只需使用这个库 - 编译 'com.google.android.gms:play-services:6.5.87'
        • 我使用 10.0.2 和 firebase,这不会导致异常吗?
        猜你喜欢
        • 2015-10-12
        • 2016-09-30
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 2012-11-26
        • 1970-01-01
        相关资源
        最近更新 更多