如何在谷歌地图android中获取当前位置

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

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

Solutions Collecting From Web of "如何在谷歌地图android中获取当前位置"

请查看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) { // TODO Auto-generated method stub mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!")); } }); } } } 

onCreate函数中调用这个函数。

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

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

文档。 获取最后一个已知位置

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

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

设置后

 googleMap.setMyLocationEnabled(true); 

你必须等到你看到你的MapView上显示的蓝点。 然后

 Location myLocation = googleMap.getMyLocation(); 

myLocation不会为空。

我想你最好使用LocationClient来实现你自己的LocationListener.onLocationChanged(Location l)

接收位置更新将告诉您如何从LocationClient获取当前位置

将权限添加到应用程序清单

添加以下权限之一作为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> 

以下代码示例在启用“我的位置”图层之前使用支持库检查权限:

 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应用代码如下,

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

为什么不使用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); } 
 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(); } } 
 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())); } } }