how to get current location in google map android

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

Actually my problem is I am not getting current location latitude and longitude I tried so many ways.I know that this question already asked in SO I tried that answers also still I didn't get answer.Please help me Code:

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

回答1:

Please check the sample code for the Google Maps Android API v2. Using this will solve your problem.

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

Call this function in onCreate function.



回答2:

I think that better way now is:

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:

Your current location might not be available immediately, after the map fragment is initialized.

After set

googleMap.setMyLocationEnabled(true); 

you have to wait until you see the blue dot shown on your MapView. Then

Location myLocation = googleMap.getMyLocation(); 

myLocation won't be null.

I think you better use the LocationClient instead, and implement your own LocationListener.onLocationChanged(Location l)

Receiving Location Updates will show you how to get current location from LocationClient



回答5:

Add the permissions to the app manifest

Add one of the following permissions as a child of the element in your Android manifest. Either the coarse location permission:

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

Or the fine location permission:

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

The following code sample checks for permission using the Support library before enabling the My Location layer:

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

This example provides current location update using GPS provider. Entire Android app code is as follows,

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


回答6:

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


回答7:

Why not to use FusedLocationApi instead of OnMyLocationChangeListener? You need to initialize GoogleApiClient object and use LocationServices.FusedLocationApi.requestLocationUpdates() method to register location change listener. It is important to note, that don't forget to remove the registered listener and disconnect 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); } 


回答8:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!