【问题标题】:How to get the current location in Google Maps Android API v2?如何在 Google Maps Android API v2 中获取当前位置?
【发布时间】:2012-12-07 02:56:32
【问题描述】:

使用

mMap.setMyLocationEnabled(true)

可以设置myLocation层启用。
但问题是当用户点击按钮时如何获取 myLocation ? 我想得到经度和纬度。

【问题讨论】:

标签: android google-maps


【解决方案1】:

Google Maps API 位置现在可以工作,甚至有监听器,您可以使用它来实现,例如:

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
        mMarker = mMap.addMarker(new MarkerOptions().position(loc));
        if(mMap != null){
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
        }
    }
};

然后为地图设置监听器:

mMap.setOnMyLocationChangeListener(myLocationChangeListener);

这将在地图第一次找到位置时被调用。

根本不需要 LocationService 或 LocationManager。

OnMyLocationChangeListener 接口已弃用。 改用 com.google.android.gms.location.FusedLocationProviderApi。 FusedLocationProviderApi 提供改进的位置查找和电源使用,并由“我的位置”蓝点使用。请参阅示例应用程序文件夹中的 MyLocationDemoActivity 以获取示例代码或位置开发人员指南。

【讨论】:

  • 很好的解决方案,但您应该在添加新的之前添加删除位置标记。在每次位置更改时,谷歌地图都会添加新的标记
  • 它现在可以工作了,但问题是有一些延迟。
  • "此接口已弃用。请改用 com.google.android.gms.location.FusedLocationProviderApi" developers.google.com/android/reference/com/google/android/gms/…
  • 太棒了,拯救了我的一天。
【解决方案2】:

目前 GoogleMap.getMyLocation() 在任何情况下总是返回 null。

据我所知,目前有两个针对 Google 的错误报告,Issue 40932Issue 4644

如前所述实施 LocationListener 是不正确的,因为 LocationListener 将与您尝试使用的新 API 中的 LocationOverlay 不同步。

按照之前由 Pramod J George 链接的 Vogella 网站上的教程,将为您提供旧版 Google Maps API 的指导。

因此,对于没有为您提供通过这种方式检索您的位置的方法,我深表歉意。目前,locationListener 可能是唯一的方法,但我确信 Google 正在努力解决新 API 中的问题。

也很抱歉没有发布更多链接,StackOverlow 认为我是垃圾邮件,因为我没有代表。

---- 2013 年 2 月 4 日更新----

Google 已声明该问题将在下次更新 Google Maps API 时通过Issue 4644 解决。我不确定什么时候会更新,但一旦更新,我会再次编辑这篇文章。

---- 2013 年 4 月 10 日更新----

Google 已通过Issue 4644 声明该问题已得到解决。它现在应该可以工作了。

【讨论】:

  • 链接线程有一个帖子说这个问题已经修复。您可能想更新您的答案。 +1
  • 我似乎仍在收到null。我在onCreate 中调用setMyLocationEnabled(true),然后在onPostCreate 中尝试getMyLocation()
  • 即使在 onPostCreate 方法中我也得到了 null
  • @mattblang 我尝试了你所说的,但我仍然在onPostCreate 方法中得到null
  • @PavelRyzhov 是的,我想我的意思是我在尝试拨打onPostCreate 时仍然收到null。问题可能是尚未获取位置,因为这是异步发生的,并且可能需要一些时间,尤其是使用 GPS。
【解决方案3】:

试试这个

LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());

【讨论】:

  • getLastKnownLocation 可以返回null,所以不够可靠
  • 这是为了获取最后一个已知位置,但不是当前位置。
【解决方案4】:

确保您已开启设备上的定位服务。 否则您将不会获得任何与位置相关的信息。

这对我有用,

    map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);
    GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange (Location location) {
           LatLng loc = new LatLng (location.getLatitude(), location.getLongitude());
           map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
        }
    };
    map.setOnMyLocationChangeListener(myLocationChangeListener);

}

【讨论】:

    【解决方案5】:

    要获取用户点击按钮时的位置,请在 onClick- 中调用此方法-

    void getCurrentLocation() {
        Location myLocation  = mMap.getMyLocation();
        if(myLocation!=null)
        {
            double dLatitude = myLocation.getLatitude();
            double dLongitude = myLocation.getLongitude();
            Log.i("APPLICATION"," : "+dLatitude);
            Log.i("APPLICATION"," : "+dLongitude);
            mMap.addMarker(new MarkerOptions().position(
                    new LatLng(dLatitude, dLongitude)).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(Utils.getBitmap("pointer_icon.png"))));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
    
        }
        else
        {
            Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
        }
    
    }
    

    还要确保

    setMyLocationEnabled

    设置为 true

    试试看是否可行...

    【讨论】:

    • Mylocation 始终为空
    • mMap.getMyLocation() 已弃用
    【解决方案6】:

    你试过GoogleMap.getMyLocation()吗?

    【讨论】:

    【解决方案7】:

    我刚刚发现这段代码 sn-p 简单而实用, 试试看:

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

    这是教程的链接:Getting the Last Known Location

    【讨论】:

      【解决方案8】:

      试试这个

      if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                      == PackageManager.PERMISSION_GRANTED) {
          mMap.setMyLocationEnabled(true);
      } else {
          // Show rationale and request permission.
      }
      

      【讨论】:

        【解决方案9】:

        试试这个

        public class MyLocationListener implements LocationListener
        {
        
         @Override
        
        public void onLocationChanged(Location loc)
        {
        
        loc.getLatitude();
        
        loc.getLongitude();
        
        String Text = “My current location is: ” +
        
        “Latitud = ” + loc.getLatitude() +
        
        “Longitud = ” + loc.getLongitude();
        
        Toast.makeText( getApplicationContext(),Text,   Toast.LENGTH_SHORT).show();
        
        
        
        tvlat.setText(“”+loc.getLatitude());
        
        tvlong.setText(“”+loc.getLongitude());
        
        this.gpsCurrentLocation();
        
        }
        

        【讨论】:

          【解决方案10】:

          它将给出当前位置。

          mMap.setMyLocationEnabled(true);
          Location userLocation = mMap.getMyLocation();
                  LatLng myLocation = null;
                  if (userLocation != null) {
                      myLocation = new LatLng(userLocation.getLatitude(),
                              userLocation.getLongitude());
                      mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
                              mMap.getMaxZoomLevel()-5));
          

          【讨论】:

            【解决方案11】:

            只有一个条件,我测试它不为空,如果您允许用户有足够的时间触摸“获取我的位置”图层按钮,那么它将不会获得空值。

            【讨论】:

              【解决方案12】:

              接受的答案有效,但现在不推荐使用一些使用的方法,所以我认为最好用更新的方法回答这个问题。

              这个答案完全来自this guide on google developers

              所以这里是一步一步的指南:

              1. 在您的地图活动中实现所有这些

                MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks

              2. 在你的onCreate:

                private GoogleMap mMap;
                private Context context;
                private TextView txtStartPoint,txtEndPoint;
                private GoogleApiClient mGoogleApiClient;
                private Location mLastKnownLocation;
                private LatLng mDefaultLocation;
                private CameraPosition mCameraPosition;
                private boolean mLocationPermissionGranted;
                
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_maps);
                context = this;
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .enableAutoManage(this /* FragmentActivity */,
                                this /* OnConnectionFailedListener */)
                        .addConnectionCallbacks(this)
                        .addApi(LocationServices.API)
                        .addApi(Places.GEO_DATA_API)
                        .addApi(Places.PLACE_DETECTION_API)
                        .build();
                mGoogleApiClient.connect();
                }
                
              3. 在您的onConnected 中:

                SupportMapFragment mapFragment = (SupportMapFragment)     getSupportFragmentManager()
                        .findFragmentById(map);
                mapFragment.getMapAsync(this);
                
              4. 在你的onMapReady

                @Override
                public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                
                // Do other setup activities here too, as described elsewhere in this tutorial.
                
                // Turn on the My Location layer and the related control on the map.
                updateLocationUI();
                
                // Get the current location of the device and set the position of the map.
                getDeviceLocation();
                }
                
              5. 这两个是onMapReady中的方法:

                private void updateLocationUI() {
                  if (mMap == null) {
                    return;
                }
                
                if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                        android.Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
                
                if (mLocationPermissionGranted) {
                    mMap.setMyLocationEnabled(true);
                    mMap.getUiSettings().setMyLocationButtonEnabled(true);
                } else {
                    mMap.setMyLocationEnabled(false);
                    mMap.getUiSettings().setMyLocationButtonEnabled(false);
                    mLastKnownLocation = null;
                }
                }
                
                private void getDeviceLocation() {
                if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                        android.Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
                
                if (mLocationPermissionGranted) {
                    mLastKnownLocation = LocationServices.FusedLocationApi
                            .getLastLocation(mGoogleApiClient);
                }
                
                // Set the map's camera position to the current location of the device.
                float DEFAULT_ZOOM = 15;
                if (mCameraPosition != null) {
                    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
                } else if (mLastKnownLocation != null) {
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(mLastKnownLocation.getLatitude(),
                                    mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                } else {
                    Log.d("pouya", "Current location is null. Using defaults.");
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
                    mMap.getUiSettings().setMyLocationButtonEnabled(false);
                }
                }
                

              这是非常快速、流畅和有效的。希望这会有所帮助

              【讨论】:

                【解决方案13】:

                我宁愿使用FusedLocationApi,因为OnMyLocationChangeListener 已被弃用。

                首先声明这3个变量:

                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);
                }
                
                • initGoogleApiClient()用于初始化GoogleApiClient对象
                • setLocationListener() 用于设置位置变化监听器
                • removeLocationListener() 用于移除监听器

                调用initGoogleApiClient 方法开始代码工作:) 不要忘记在最后删除监听器(mLocationListener)以避免内存泄漏问题。

                【讨论】:

                  猜你喜欢
                  • 2012-11-30
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-08-27
                  • 1970-01-01
                  • 1970-01-01
                  • 2014-12-25
                  • 1970-01-01
                  相关资源
                  最近更新 更多