简体   繁体   中英

Google maps Android API and current location

I am trying to implement the google maps API. I want to see my own position on the map and I want that it changes when I move significantly. The problem is that there are no errors but it does not display a marker of my position on the map. This is my onCreate() methode in the .java file

private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public static final String TAG = MapPane.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map_pane);
    // 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);

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}//onCreate

And this is the method I think I am missing here something

 public void onConnected(@Nullable Bundle bundle) {
    Log.i(TAG, "Location services connected.");

    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        Log.i(TAG, "loc exists");
        if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }//if
    }//if
    else {
        handleNewLocation(location);
    }//else
}//onConnected

because I never get into the second if statement. I guess I need the permission of the user first? Turning the gps on manually on my device does not work either. And the method below I used for displaying the marker on the map

private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    MarkerOptions options = new MarkerOptions()
            .position(latLng)
            .title("I am here!");
    mMap.addMarker(options);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

}//handleNewLocation

I used more methods but I think there is no flaw in there. In the AndroidManifest.xml I included

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

You can use LocationManager instead of google api client

             LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    final Geocoder gc = new Geocoder(this, Locale.getDefault());

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //here you can get current position location.getLatitude(),location.getLongitude();

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

It seems your code is not providing any location to the handlelocation() method.

private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public static final String TAG = MapPane.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
LocationListener li;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map_pane);
    // Obtain the SupportMapFragment and get notified when the map is reato be used.
    SupportMapFragment mapFragment = (SupportMapFragment)         getSupportFragmentManager()
        .findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

 li=new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            handleNewLocation(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };


  getHandledCurrentLocation();
}//onCr

private void getHandledCurrentLocation() {
    String locationProvider = LocationManager.NETWORK_PROVIDER;

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
    }
    Log.e("LOCATION_DEBUG","LOCATION REQUESTED--- ");
    LCM.requestLocationUpdates(locationProvider, 10 * 1000, 0,li);

}
private void handleNewLocation(Location location) {
 Log.d(TAG, location.toString());
 double currentLatitude = location.getLatitude();
 double currentLongitude = location.getLongitude();
 LatLng latLng = new LatLng(currentLatitude, currentLongitude);

 MarkerOptions options = new MarkerOptions()
        .position(latLng)
        .title("I am here!");
 mMap.addMarker(options);
 mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

}//handleNewLocation

this code should work.

I can see few issues with your code. I don't think you are handling the location updates provided by FusedLocationApi. I believe you are implementing LocationListener even though that part of the code is not provided in your question. In that case you are implementing a method ' onLocationChanged(Location location) ' in your activity. This is the method in which you should try to set the new location on the map. Your handleNewLocation method will not be called by FusedLocationApi automatically

You may want to provide the complete code for your activity , then we can help you better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM