【问题标题】:how to get current location in google map android如何在谷歌地图android中获取当前位置
【发布时间】:2014-02-19 15:03:57
【问题描述】:

实际上我的问题是我没有得到当前位置的纬度和经度我尝试了很多方法。我知道这个问题已经问过所以我尝试了答案仍然我没有得到答案。请帮助我 代码:

    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
    googleMap.setMyLocationEnabled(true);
    Location myLocation = googleMap.getMyLocation();  //Nullpointer exception.........
    LatLng myLatLng = new LatLng(myLocation.getLatitude(),
            myLocation.getLongitude());

    CameraPosition myPosition = new CameraPosition.Builder()
            .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
    googleMap.animateCamera(
        CameraUpdateFactory.newCameraPosition(myPosition));

【问题讨论】:

标签: android google-maps


【解决方案1】:

请查看Google Maps Android API v2 的示例代码。使用它可以解决您的问题。

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        mMap.setMyLocationEnabled(true);
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                @Override
                public void onMyLocationChange(Location arg0) {
                    mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
                }
            });
        }
    }
}

onCreate函数中调用这个函数。

更新:

方法 mMap.setOnMyLocationChangeListener 现已弃用,您现在需要使用 FusedLocationProviderClient

private FusedLocationProviderClient fusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}

要请求最后一个已知位置,请调用 getLastLocation() 方法。以下代码 sn -p 说明了请求和响应的简单处理:

fusedLocationClient.getLastLocation()
        .addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location. In some rare situations this can be null.
                if (location != null) {
                    // Logic to handle location object
                }
            }
        });

参考:https://developer.android.com/training/location/retrieve-current.html

【讨论】:

【解决方案2】:

我认为现在更好的方法是:

Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

Documentation. Getting the Last Known Location

【讨论】:

【解决方案3】:
package com.example.sandeep.googlemapsample;

import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMarkerDragListener,
        GoogleMap.OnMapLongClickListener,
        GoogleMap.OnMarkerClickListener,
        View.OnClickListener {

    private static final String TAG = "MapsActivity";
    private GoogleMap mMap;
    private double longitude;
    private double latitude;
    private GoogleApiClient googleApiClient;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //Initializing googleApiClient
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
       // googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID)
                    //    .compassEnabled(true);

        // Add a marker in Sydney and move the camera
        LatLng india = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(india).title("Marker in India"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(india));
        mMap.setOnMarkerDragListener(this);
        mMap.setOnMapLongClickListener(this);
    }

    //Getting current location
    private void getCurrentLocation() {
        mMap.clear();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();

            //moving the map to location
            moveMap();
        }
    }

    private void moveMap() {
        /**
         * Creating the latlng object to store lat, long coordinates
         * adding marker to map
         * move the camera with animation
         */
        LatLng latLng = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true)
                .title("Marker in India"));

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mMap.getUiSettings().setZoomControlsEnabled(true);


    }

    @Override
    public void onClick(View view) {
        Log.v(TAG,"view click event");
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        getCurrentLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        // mMap.clear();
        mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
    }

    @Override
    public void onMarkerDragStart(Marker marker) {
        Toast.makeText(MapsActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMarkerDrag(Marker marker) {
        Toast.makeText(MapsActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        // getting the Co-ordinates
        latitude = marker.getPosition().latitude;
        longitude = marker.getPosition().longitude;

        //move to current position
        moveMap();
    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        Toast.makeText(MapsActivity.this, "onMarkerClick", Toast.LENGTH_SHORT).show();
        return true;
    }

}

【讨论】:

【解决方案4】:

如果您不需要在每次更改用户位置时都检索它(我不知道为什么几乎每个解决方案都使用位置侦听器来做到这一点),那么这样做只是浪费。提问者显然对只检索一次位置感兴趣。现在 FusedLocationApi 已被弃用,因此作为@Andrey 帖子的替代品,您可以这样做:


    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    String locationProvider = LocationManager.NETWORK_PROVIDER;
    // I suppressed the missing-permission warning because this wouldn't be executed in my 
    // case without location services being enabled
    @SuppressLint("MissingPermission") android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
    double userLat = lastKnownLocation.getLatitude();
    double userLong = lastKnownLocation.getLongitude();

这只是将文档中的一些零散信息汇总在一起,this 是最重要的来源。

【讨论】:

  • 太棒了!这正是我一直在寻找的。非常感谢,你拯救了我的一天。
  • 完美运行。我刚刚将this 更改为getContext(),因为我在片段中使用了您的代码
【解决方案5】:

MapsActivity 类中的这段代码对我有用:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;

public void centreMapOnLocation(Location location, String title){

    LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
    mMap.clear();
    mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,12));

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);

            Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            centreMapOnLocation(lastKnownLocation,"Your Location");
        }
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps2);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    Intent intent = getIntent();
    if (intent.getIntExtra("Place Number",0) == 0 ){

        // Zoom into users location
        locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                centreMapOnLocation(location,"Your Location");
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                centreMapOnLocation(lastKnownLocation,"Your Location");
        } else {

            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
        }
    }


}


}

【讨论】:

    【解决方案6】:

    在地图片段初始化后,您的当前位置可能不会立即可用。

    设置后

    googleMap.setMyLocationEnabled(true);
    

    您必须等到看到 MapView 上显示的蓝点。那么

    Location myLocation = googleMap.getMyLocation();
    

    myLocation 不会为空。

    我认为你最好改用LocationClient,并实现你自己的LocationListener.onLocationChanged(Location l)

    Receiving Location Updates 将向您展示如何从 LocationClient 获取当前位置

    【讨论】:

    • getMyLocation 已弃用
    【解决方案7】:
    1. 选择谷歌地图活动

    2. 您需要一个 Google Maps API 密钥。

      要获得一个,请点击此链接,按照说明操作,最后按“创建”: https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=48:C7:A8:5B:31:4F:78:F2:38:41:97:F4:70:C3:A0:EB:6A:73:28:88%3Bcom.example.myapplication

    3. 将此代码粘贴到 MapsActivity.java

    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.os.Build;
    
    import android.os.Bundle;
    
    import android.widget.Toast;
    
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.fragment.app.FragmentActivity;
    
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.BitmapDescriptorFactory;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;
    
    
    
      public class MapsActivity extends FragmentActivity implement
       OnMapReadyCallback,
       GoogleApiClient.ConnectionCallbacks,
       GoogleApiClient.OnConnectionFailedListener,
      LocationListener{
    
        @private GoogleMap mMap;
            GoogleApiClient mGoogleApiClient;
            Location mLastLocation;
            Marker mCurrLocationMarker;
            LocationRequest mLocationRequest;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_maps);
    
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkLocationPermission();
                }
                // Obtain the SupportMapFragment and get notified when the map is ready to be used.
                SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
                mapFragment.getMapAsync(this);
            }
    
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
    
    
                //Initialize Google Play Services
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION) ==
                        PackageManager.PERMISSION_GRANTED) {
                        buildGoogleApiClient();
                        mMap.setMyLocationEnabled(true);
                    }
                } else {
                    buildGoogleApiClient();
                    mMap.setMyLocationEnabled(true);
                }
            }
    
            protected synchronized void buildGoogleApiClient() {
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
                mGoogleApiClient.connect();
            }
    
            @Override
            public void onConnected(Bundle bundle) {
    
                mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(1000);
                mLocationRequest.setFastestInterval(1000);
                mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED) {
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                }
    
            }
    
            @Override
            public void onConnectionSuspended(int i) {
    
            }
    
            @Override
            public void onLocationChanged(Location location) {
    
                mLastLocation = location;
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker.remove();
                }
    
                //Place current location marker
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title("Current Position");
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                mCurrLocationMarker = mMap.addMarker(markerOptions);
    
                //move map camera
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    
                //stop location updates
                if (mGoogleApiClient != null) {
                    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                }
    
            }
    
            @Override
            public void onConnectionFailed(ConnectionResult connectionResult) {
    
            }
    
            public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
            public boolean checkLocationPermission() {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED) {
    
                    // Asking user if explanation is needed
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)) {
    
                        // Show an explanation to the user *asynchronously* -- don't block
                        // this thread waiting for the user's response! After the user
                        // sees the explanation, try again to request the permission.
    
                        //Prompt the user once explanation has been shown
                        ActivityCompat.requestPermissions(this,
                            new String[] {
                                Manifest.permission.ACCESS_FINE_LOCATION
                            },
                            MY_PERMISSIONS_REQUEST_LOCATION);
    
    
                    } else {
                        // No explanation needed, we can request the permission.
                        ActivityCompat.requestPermissions(this,
                            new String[] {
                                Manifest.permission.ACCESS_FINE_LOCATION
                            },
                            MY_PERMISSIONS_REQUEST_LOCATION);
                    }
                    return false;
                } else {
                    return true;
                }
            }
    
            @Override
            public void onRequestPermissionsResult(int requestCode,
                String permissions[], int[] grantResults) {
                switch (requestCode) {
                    case MY_PERMISSIONS_REQUEST_LOCATION:
                        {
                            // If request is cancelled, the result arrays are empty.
                            if (grantResults.length > 0 &&
                                grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                                // permission was granted. Do the
                                // contacts-related task you need to do.
                                if (ContextCompat.checkSelfPermission(this,
                                        Manifest.permission.ACCESS_FINE_LOCATION) ==
                                    PackageManager.PERMISSION_GRANTED) {
    
                                    if (mGoogleApiClient == null) {
                                        buildGoogleApiClient();
                                    }
                                    mMap.setMyLocationEnabled(true);
                                }
    
                            } else {
    
                                // Permission denied, Disable the functionality that depends on this permission.
                                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                            }
                            return;
                        }
    
    
                }
            }
        }
    
    1. 确保这些权限写在 Manifest 文件中

      &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt;

    2. 添加以下依赖项

      implementation 'com.google.android.gms:play-services-maps:17.0.0'

      implementation 'com.google.android.gms:play-services-location:17.0.0'

    【讨论】:

    • onRequestPermissionsResult 已弃用。这种方法的替代品应该是什么。
    【解决方案8】:
    Location locaton;
    
    private GoogleMap mMap;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    
    
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
    
        mMap.setMyLocationEnabled(true);
    
        mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
    
                CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
                mMap.clear();
    
                MarkerOptions mp = new MarkerOptions();
    
                mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
    
                mp.title("my position");
    
                mMap.addMarker(mp);
                mMap.moveCamera(center);
                mMap.animateCamera(zoom);
    
            }
        });}}
    

    【讨论】:

    • setOnMyLocationChangeListener 已被弃用,所以现在我们用什么来处理这种行为?
    • @ArslanMaqbool,见stackoverflow.com/a/53851018/2914140:使用OnCamera...Listener
    【解决方案9】:

    FusedLocationApi 一直是Deprecated(为什么 Google 总是弃用一切!)

    location: retrieve-current

    现在获取方法如下:

    private lateinit var fusedLocationClient: FusedLocationProviderClient
    
    override fun onCreate(savedInstanceState: Bundle?) {
        // ...
    
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    }
    

    【讨论】:

      【解决方案10】:
      public void getMyLocation() {
              // create class object
              gps = new GPSTracker(HomeActivity.this);
              // check if GPS enabled
              if (gps.canGetLocation()) {
                  latitude = gps.getLatitude();
                  longitude = gps.getLongitude();
                  Geocoder geocoder;
                  List<Address> addresses;
                  geocoder = new Geocoder(this, Locale.getDefault());
                  try {
                      addresses = geocoder.getFromLocation(latitude, longitude, 1);
                      postalCode = addresses.get(0).getPostalCode();
                      city = addresses.get(0).getLocality();
                      address = addresses.get(0).getAddressLine(0);
                      state = addresses.get(0).getAdminArea();
                      country = addresses.get(0).getCountryName();
                      knownName = addresses.get(0).getFeatureName();
                      Log.e("Location",postalCode+" "+city+" "+address+" "+state+" "+knownName);
      
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              } else {
                  gps.showSettingsAlert();
              }
          }
      

      【讨论】:

        【解决方案11】:

        上面提到的所有解决方案都使用了现在已弃用的代码!这是新的解决方案

        1. 在您的 gradle 文件中添加实现 'com.google.android.gms:play-services-places:15.0.1' 依赖项

        2. 在清单文件中添加网络权限:

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

        1. 现在使用此代码获取当前位置

            FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
          
            mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                          @Override
                          public void onSuccess(Location location) {
                              // GPS location can be null if GPS is switched off
                                  currentLat = location.getLatitude();
                                  currentLong = location.getLongitude();
                                  Toast.makeText(HomeNavigationBarActivtiy.this, "lat " + location.getLatitude() + "\nlong " + location.getLongitude(), Toast.LENGTH_SHORT).show();
                          }
                      })
                      .addOnFailureListener(new OnFailureListener() {
                          @Override
                          public void onFailure(@NonNull Exception e) {
                              e.printStackTrace();
                          }
                      });
          

        【讨论】:

        • 此解决方案还需要授予权限。
        【解决方案12】:

        将权限添加到应用清单

        在您的 Android 清单中添加以下权限之一作为元素的子项。粗略位置权限:

        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.example.myapp" >
          ...
          <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
          ...
        </manifest>
        

        或者精细定位权限:

        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.example.myapp" >
          ...
          <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
          ...
        </manifest>
        

        以下代码示例在启用 My Location 层之前使用 Support 库检查权限:

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            // Show rationale and request permission.
        }
        The following sample handles the result of the permission request by implementing the ActivityCompat.OnRequestPermissionsResultCallback from the Support library:
        
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            if (requestCode == MY_LOCATION_REQUEST_CODE) {
              if (permissions.length == 1 &&
                  permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
                  grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mMap.setMyLocationEnabled(true);
            } else {
              // Permission was denied. Display an error message.
            }
        }
        

        此示例使用 GPS 提供程序提供当前位置更新。整个Android app代码如下,

        import android.os.Bundle;
        import android.app.Activity;
        import android.content.Context;
        import android.location.Location;
        import android.location.LocationListener;
        import android.location.LocationManager;
        import android.widget.TextView;
        
        import android.util.Log;
        
        public class MainActivity extends Activity implements LocationListener{
        protected LocationManager locationManager;
        protected LocationListener locationListener;
        protected Context context;
        TextView txtLat;
        String lat;
        String provider;
        protected String latitude,longitude; 
        protected boolean gps_enabled,network_enabled;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtLat = (TextView) findViewById(R.id.textview1);
        
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }
        @Override
        public void onLocationChanged(Location location) {
        txtLat = (TextView) findViewById(R.id.textview1);
        txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
        }
        
        @Override
        public void onProviderDisabled(String provider) {
        Log.d("Latitude","disable");
        }
        
        @Override
        public void onProviderEnabled(String provider) {
        Log.d("Latitude","enable");
        }
        
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d("Latitude","status");
        }
        }
        

        【讨论】:

          【解决方案13】:

          在谷歌地图上获取当前位置的简单步骤:

          1 - 创建地图活动,以便在 onMap 就绪方法中创建 LocationManager 和 LocationListener

          2 - 在 onMap 中,您还可以检查 android 版本和用户权限 ==> 如果有权限,则提供位置更新或请求用户许可

          3 - 在主类中检查权限结果 (onRequestPermissionsResult) ==> 如果条件为真,则更新位置

          4 - 在 (onLocationChanged) 方法中,我们创建 LatLng 变量并从位置获取坐标,然后从 mMap 我们(addMarker 和 moveCamera)为我们刚刚创建的那个变量提供坐标,当用户移动时,这给了我们位置,所以我们仍然需要在 onMap 中创建新的 LatLng,以便在应用程序启动时获得用户的位置 ==>如果有权限(lastKnownLocation),则内部条件。

          注意:

          1) 不要忘记在 Manifest 中请求权限(位置和 Internet)

          2) 不要忘记从谷歌 API 获取 Map 密钥

          3) 我们使用 (mMap.clear) 来避免每次(运行应用或更新位置)时重复标记

          编码部分

          public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
          
              private GoogleMap mMap;
              LocationManager locationManager;
              LocationListener locationListener;
          
              @Override
              public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
                  super.onRequestPermissionsResult(requestCode, permissions, grantResults);
          
                  if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                      if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                          locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                      }
                  }
              }
          
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_maps);
                  SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                          .findFragmentById(R.id.map);
                  mapFragment.getMapAsync(this);
          
          
              }
          
              @SuppressLint("MissingPermission")
              @Override
              public void onMapReady(GoogleMap googleMap) {
                  mMap = googleMap;
          
                  locationManager  = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
          
                  locationListener = new LocationListener() {
                      @Override
                      public void onLocationChanged(Location location) {
          
                          mMap.clear();
          
                          LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
          
                          mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker"));
          
                          mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
          
                          Toast.makeText(MapsActivity.this, userLocation.toString(), Toast.LENGTH_SHORT).show();
                      }
          
                      @Override
                      public void onStatusChanged(String provider, int status, Bundle extras) {
          
          
                      }
          
                      @Override
                      public void onProviderEnabled(String provider) {
          
                      }
          
                      @Override
                      public void onProviderDisabled(String provider) {
          
                      }
          
          
                  };
          
                  if (Build.VERSION.SDK_INT < 23 ){
          
                      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
          
                  }else if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
          
                      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
          
                      Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
          
                      LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
          
                      mMap.clear();
          
                      mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker"));
          
                      mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
          
                      Toast.makeText(MapsActivity.this, userLocation.toString(), Toast.LENGTH_SHORT).show();
          
          
                  } else {
          
                      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
          
                  }
          
          
              }
          
          
              }
          }
          

          【讨论】:

            【解决方案14】:
            //check this condition if (Build.VERSION.SDK_INT < 23 ) 
            

            在某些 android studio 中,当整个代码工作时,它不起作用,因此将这一行替换为:

            if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
            

            &我的项目运行良好。

            【讨论】:

              【解决方案15】:
                       import android.Manifest;
              import android.content.pm.PackageManager;
              import android.location.Address;
              import android.location.Geocoder;
              import android.location.Location;
              import android.os.Build;
              import android.os.Bundle;
              
              import androidx.annotation.RequiresApi;
              import androidx.core.app.ActivityCompat;
              import androidx.fragment.app.FragmentActivity;
              
              import com.google.android.gms.location.FusedLocationProviderClient;
              import com.google.android.gms.location.LocationListener;
              import com.google.android.gms.location.LocationServices;
              import com.google.android.gms.maps.CameraUpdateFactory;
              import com.google.android.gms.maps.GoogleMap;
              import com.google.android.gms.maps.OnMapReadyCallback;
              import com.google.android.gms.maps.SupportMapFragment;
              import com.google.android.gms.maps.model.LatLng;
              import com.google.android.gms.maps.model.MarkerOptions;
              import com.google.android.gms.tasks.OnSuccessListener;
              
              import java.io.IOException;
              import java.util.List;
              import java.util.Locale;
              
              import static android.Manifest.permission.ACCESS_FINE_LOCATION;
              
              public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
              
                  private GoogleMap mMap;
                  private FusedLocationProviderClient client;
                  double latit;
                  double longi;
              
                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.activity_maps);
                      // Obtain the SupportMapFragment and get notified when the map is ready to be used.
                      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                              .findFragmentById(R.id.map);
                      mapFragment.getMapAsync(this);
                      client = LocationServices.getFusedLocationProviderClient(this);
                  }
              @RequiresApi(api = Build.VERSION_CODES.M)
                  @Override
                  public void onMapReady(GoogleMap googleMap) {
                      mMap = googleMap;
              
              
              
                      try {
                          setupMap();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
              
                  }
               client = LocationServices.getFusedLocationProviderClient(this);
              
                      if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                          // TODO: Consider calling
                          //    Activity#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 Activity#requestPermissions for more details.
                          return;
                      }
                      client.getLastLocation()
                              .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                                  @Override
                                  public void onSuccess(Location location) {
                                      // Got last known location. In some rare situations this can be null.
                                      if (location != null) {
              
                                          //    local=findViewById(R.id.tv5);
              
                                          double la=location.getLatitude();
                                          double lo=location.getLongitude();
              
                                          LatLng curre=new LatLng(la,lo);
                                          mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curre,18));
              
                                      }
                                  }
                              });
              
              
              
                  }
                  }
              

              【讨论】:

              • 你能解释一下这个答案,让它不仅仅是一大块代码吗?
              【解决方案16】:

              从 Google 示例 (CurrentPlaceDetailsOnMap)kotlinFusedLocationProviderClientsetOnMyLocationChangeListenerdeprecated

              首先将implementation 'com.google.android.libraries.places:places:2.4.0' 添加到dependencies

              接下来在你的fragment 中添加这些变量

              private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
              private var lastKnownLocation: Location? = null
              

              onViewCreated 下一个添加这个

                  fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireContext())
              

              onMapReady调用这个方法

              private fun getDeviceLocation() {
                  /*
                   * Get the best and most recent location of the device, which may be null in rare
                   * cases when a location is not available.
                   */
                  try {
                          val locationResult = fusedLocationProviderClient.lastLocation
                          locationResult.addOnCompleteListener(context as Activity) { task ->
                              if (task.isSuccessful) {
                                  // Set the map's camera position to the current location of the device.
                                  lastKnownLocation = task.result
                                  if (lastKnownLocation != null) {
                                      mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                              LatLng(lastKnownLocation!!.latitude,
                                                      lastKnownLocation!!.longitude), DEFAULT_ZOOM.toFloat()))
                                  }
                              } else {
                                  logD("Current location is null. Using defaults.")
                                  logD("Exception: ${task.exception}")
                                  mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(35.6892, 51.3890), 15.toFloat()))
                                  mMap.uiSettings?.isMyLocationButtonEnabled = false
                              }
                          }
                  } catch (e: SecurityException) {
                      logD("Exception: ${e.message}")
                  }
              }
              

              如果lastKnownLocation 为空,你应该用这个方法更新它:

              fun requestLocation(context: Context) {
                      val mLocationRequest = LocationRequest.create()
                      mLocationRequest.interval = 60000
                      mLocationRequest.fastestInterval = 5000
                      mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
                      val mLocationCallback: LocationCallback = object : LocationCallback() {
                          override fun onLocationResult(locationResult: LocationResult) {
                              for (location in locationResult.locations) {
                                  if (location != null && lastKnownLocation == null) {
                                      lastKnownLocation = location
                                  }
                              }
                          }
                      }
                      LocationServices.getFusedLocationProviderClient(context)
                          .requestLocationUpdates(mLocationRequest, mLocationCallback, null)
                  }
              

              如果你愿意,你可以通过这个打开你的位置

              mMap.isMyLocationEnabled = true
              mMap.uiSettings.isMyLocationButtonEnabled = false
              

              【讨论】:

                【解决方案17】:

                为什么不使用FusedLocationApi 而不是OnMyLocationChangeListener?您需要初始化 GoogleApiClient 对象并使用LocationServices.FusedLocationApi.requestLocationUpdates() 方法注册位置更改侦听器。需要注意的是,不要忘记删除注册的监听器并断开GoogleApiClient

                private LocationRequest  mLocationRequest;
                private GoogleApiClient  mGoogleApiClient;
                private LocationListener mLocationListener;
                
                private void initGoogleApiClient(Context context)
                {
                    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
                    {
                        @Override
                        public void onConnected(Bundle bundle)
                        {
                            mLocationRequest = LocationRequest.create();
                            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                            mLocationRequest.setInterval(1000);
                
                            setLocationListener();
                        }
                
                        @Override
                        public void onConnectionSuspended(int i)
                        {
                            Log.i("LOG_TAG", "onConnectionSuspended");
                        }
                    }).build();
                
                    if (mGoogleApiClient != null)
                        mGoogleApiClient.connect();
                
                }
                
                private void setLocationListener()
                {
                    mLocationListener = new LocationListener()
                    {
                        @Override
                        public void onLocationChanged(Location location)
                        {
                            String lat = String.valueOf(location.getLatitude());
                            String lon = String.valueOf(location.getLongitude());
                            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
                        }
                    };
                
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
                }
                
                private void removeLocationListener()
                {
                    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
                }
                

                【讨论】:

                  【解决方案18】:
                  public class MainActivity extends ActionBarActivity implements
                      ConnectionCallbacks, OnConnectionFailedListener {
                  ...
                  @Override
                  public void onConnected(Bundle connectionHint) {
                      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                              mGoogleApiClient);
                      if (mLastLocation != null) {
                          mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
                          mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
                      }
                  }
                  }
                  

                  【讨论】:

                    猜你喜欢
                    • 2021-09-11
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2012-11-26
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多