简体   繁体   中英

Tracking current location on Google Maps

I've tried to make an app that has a map activity that as soon as it is opened , the map starts on the users current location. I tried to use guides and help online but it seems that all of these guides are outdated because they have the onResume and onStart method by default in the maps activity and instead i have the onMapReady method and none of these methods. this is the code that i tried writing but it does not work(app crashes),

package com.imt.civilwatch;
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 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.MarkerOptions;
import java.text.StringCharacterIterator;
public class MapActivity extends FragmentActivity implements         OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
Location mLastLocation;
private double mLatitudeText;
private double mLongitudeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    // 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);
}
protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}
protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(32, 35);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    //mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
@Override
public void onConnected(Bundle connectionHint) {
    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;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        mLatitudeText = (Double.valueOf(mLastLocation.getLatitude()));
        mLongitudeText = (Double.valueOf(mLastLocation.getLongitude()));
        LatLng last = new LatLng( mLatitudeText,mLongitudeText);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(last));
    }
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}

}

The method onMapReady runs when the map's fragment is ready and displaying the map.

The onConnected method runs when the device successfully connects with Google Play Location service and (if available) gets your last known location.

If you don't want the camera moving to your current location, delete whats between this condition:

if(mLastLocation != null){...}

For maps, the camera is what's visible on screen. The method mMap.moveCamera(...) tells Map to center the view at specific LatLng.

If your map is ready before your phone connects with Google Play Location API, the current location visible will be this:

if (mLastLocation != null) {
    mLatitudeText = (Double.valueOf(mLastLocation.getLatitude()));
    mLongitudeText = (Double.valueOf(mLastLocation.getLongitude()));
    LatLng last = new LatLng( mLatitudeText,mLongitudeText);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(last));
}

Hope I was clear.


See the CameraFactory docs to learn about camera manipulation on Maps: https://developers.google.com/android/reference/com/google/android/gms/maps/CameraUpdateFactory

From the documentation of Google Maps Android API, the location data available to an Android device includes the current location of the device pinpointed using a combination of technologies - the direction and method of movement, and whether the device has moved across a predefined geographical boundary, or geofence.

Depending upon the needs of your application, you can choose between these options:

  • Using My Location layer that provides a simple way to display the device's location on the map. It does not provide data.

  • Using Google Play services Location API is recommended for all programmatic requests for location data.

  • And using the LocationSource interface allows you to provide a custom location provider.

For more information, check this tutorial on how to get the current location:

Bro You Need The GoogleApiClient and LocationRequest for this , and also in manifest two users permission that are "ACCESS FINE LOCATION AND ACCESS COARSE LOCATION" and in order to get the current Location You need to do such something like this: Include This in Manifest:-

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

--> And Current Location Code in Acticity will be like this: --> Create These Two Variables Globely in the Activity:

GoogleApiClient mGoogleapiClient;
LocationRequest mUserLocationRequest;

--> Then Come To the @override Onconnected() and do like this :-

 @Override
public void onConnected(Bundle bundle) {
    mUserLocationRequest = LocationRequest.create();
    /* Priority = High so that more Correct User Location will be Accessed
       up to date information ot highest information get*/
    /* Priority = Low if you Don't Want The Exect Location Of The User */
    mUserLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    /*For every 1 min I have to Fetch My User Location*/
    mUserLocationRequest.setInterval(1000);

    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;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleapiClient, mUserLocationRequest,  (LocationListener) MainActivity.this);
}

--> Now Impelents The LocationListener in Activity which implents the Method onLocationChanged(): and do such stuff in this , that will give you up to date info whenever user changes its Location:-

@Override
public void onLocationChanged(Location location) {
    if (location == null)
    {
        Toast.makeText(this, "Sorry We Can't able to Get Your Current Location", Toast.LENGTH_SHORT).show();
    }
    else
    {
        LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng,15);
        mGoogleMap.animateCamera(update);
    }
}

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