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

时间:2023-02-05 20:21:34

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

11 个解决方案

#1


40  

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

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

            }
        }
    }

Call this function in onCreate function.

在onCreate函数中调用此函数。

#2


12  

I think that better way now is:

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

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

Documentation. Getting the Last Known Location

文档。获取最后的位置

#3


6  

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


2  

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

#5


2  

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

        }
    });}}

#6


1  

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

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

Location myLocation = googleMap.getMyLocation();

myLocation won't be null.

myLocation不会为null。

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

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

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

接收位置更新将显示如何从LocationClient获取当前位置

#7


1  

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:

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

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,

此示例使用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");
}
}

#8


0  

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.

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

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

#9


0  

This Code in MapsActivity Class works for me :

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


}


}

#10


-1  

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

#11


-1  

Simple steps to get current location on google map:

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

1 - create map activity so in onMap ready method you create LocationManager and LocationListener

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

2 - in onMap ready also you check for android version and user permission ==> if there is a permission give location update OR ask the user for permission

2 - 在onMap ready中也检查android版本和用户权限==>如果有权限给位置更新或要求用户许可

3 - in the main class check for result of permission (onRequestPermissionsResult) ==> if the condition is true so give location update

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

4 - in (onLocationChanged) method we create LatLng variable and get the coordinates from location then from mMap we (addMarker and moveCamera) for that variable we've just created, this gives us location when the user moves so we still need to create new LatLng in onMap ready to have user's location when the App starts ==>inside condition if there is permission (lastKnownLocation).

4 - in(onLocationChanged)方法我们创建LatLng变量并从位置获取坐标,然后从mMap我们(addMarker和moveCamera)获取我们刚创建的变量,这为我们提供了位置,当用户移动时我们仍然需要创建新的如果有权限(lastKnownLocation),onMap中的LatLng准备在App启动时拥有用户的位置==>内部条件。

NOTE:

注意:

1) Do Not forget to ask for permissions (Location and Internet) in Manifest

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

2) Do Not forget to have Map key from google APIs

2)不要忘记从谷歌API获得地图密钥

3) We used (mMap.clear) to avoid repeating the marker each time we (run the app or update location)

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

Coding Part:

编码部分:

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

        }


    }


    }
}

#1


40  

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

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

            }
        }
    }

Call this function in onCreate function.

在onCreate函数中调用此函数。

#2


12  

I think that better way now is:

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

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

Documentation. Getting the Last Known Location

文档。获取最后的位置

#3


6  

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


2  

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

#5


2  

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

        }
    });}}

#6


1  

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

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

Location myLocation = googleMap.getMyLocation();

myLocation won't be null.

myLocation不会为null。

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

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

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

接收位置更新将显示如何从LocationClient获取当前位置

#7


1  

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:

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

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,

此示例使用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");
}
}

#8


0  

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.

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

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

#9


0  

This Code in MapsActivity Class works for me :

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


}


}

#10


-1  

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

#11


-1  

Simple steps to get current location on google map:

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

1 - create map activity so in onMap ready method you create LocationManager and LocationListener

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

2 - in onMap ready also you check for android version and user permission ==> if there is a permission give location update OR ask the user for permission

2 - 在onMap ready中也检查android版本和用户权限==>如果有权限给位置更新或要求用户许可

3 - in the main class check for result of permission (onRequestPermissionsResult) ==> if the condition is true so give location update

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

4 - in (onLocationChanged) method we create LatLng variable and get the coordinates from location then from mMap we (addMarker and moveCamera) for that variable we've just created, this gives us location when the user moves so we still need to create new LatLng in onMap ready to have user's location when the App starts ==>inside condition if there is permission (lastKnownLocation).

4 - in(onLocationChanged)方法我们创建LatLng变量并从位置获取坐标,然后从mMap我们(addMarker和moveCamera)获取我们刚创建的变量,这为我们提供了位置,当用户移动时我们仍然需要创建新的如果有权限(lastKnownLocation),onMap中的LatLng准备在App启动时拥有用户的位置==>内部条件。

NOTE:

注意:

1) Do Not forget to ask for permissions (Location and Internet) in Manifest

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

2) Do Not forget to have Map key from google APIs

2)不要忘记从谷歌API获得地图密钥

3) We used (mMap.clear) to avoid repeating the marker each time we (run the app or update location)

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

Coding Part:

编码部分:

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

        }


    }


    }
}