如何获取Google Maps Android API v2中的当前位置?

运用

mMap.setMyLocationEnabled(true) 

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

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

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

完全不需要LocationService或LocationManager。

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

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

目前有两个谷歌的错误报告,我知道, 问题40932和问题4644 。

实现前面提到的LocationListener将是不正确的,因为LocationListener将与您试图使用的新API中的LocationOverlay不同步。

继Pramod J George之前链接到Vogella网站的教程之后,它将为您提供老Google Maps API的指导。

所以我很抱歉没有给你一个方法来检索你的位置的手段。 目前,locationListener可能是唯一的手段,但我相信Google正在努力解决这个问题。

也抱歉不张贴更多的链接,StackOverlow认为我是垃圾邮件,因为我没有代表。

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

谷歌已经表示,这个问题将在谷歌地图API的下一次更新中通过问题4644解决 。 我不知道什么时候更新会发生,但一旦我做了,我会再次编辑这个post。

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

谷歌已经表示,这个问题已经通过问题4644解决 。 它应该现在工作。

尝试这个

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

确保已打开设备上的位置服务。 否则你不会得到任何位置相关的信息。

这对我有用,

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

}

要获取用户点击button时的位置,请在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

尝试看看这是否工作…

你有没有尝试过GoogleMap.getMyLocation()

我刚刚发现这个代码片断简单而实用,试试:

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

这里是教程的链接: 获取最后一个已知位置

尝试这个

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

尝试这个

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

它会给当前的位置。

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

只有一个条件,我testing它不是null是,如果你有足够的时间用户触摸“我的位置”图层button,那么它不会得到空值。

被接受的答案的作品,但一些使用的方法已被弃用,所以我认为这是最好的,如果我用更新的方法回答这个问题。

这个答案完全是来自Google开发者的这个指南

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

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

这是非常快速,顺畅和有效的。 希望这可以帮助

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

首先声明这3个variables:

 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 )以避免内存泄漏问题。