如何在谷歌地图中显示更新的当前位置

4

我试图在地图上显示当前更新的位置。

当我缩放地图并且位置更新时,它会缩小地图然后显示位置。它不会在同一缩放位置上显示更新的位置。 当位置更新时,我会在地图上重新设置标记。我认为问题在于在地图上设置标记。请帮助我在地图上显示当前更新的位置。

public class MainActivity extends FragmentActivity implements OnMapReadyCallback , GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

GoogleMap googleMa;
double latitude;
private GoogleApiClient mGoogleApiClient;
double longitude;
private Location mLastLocation = null;
private LocationRequest mLocationRequest;
String mPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
protected LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
            2);

    locationManager = (LocationManager) MainActivity.this
            .getSystemService(Context.LOCATION_SERVICE);
   boolean isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (checkPlayServices()) {

        buildGoogleApiClient();
        createLocationRequest();
        displayLocation();

    }
    initailizeMap();
}

public void initailizeMap() {
    if (googleMa == null) {
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    googleMa = googleMap;
    Log.d("aaaaaa", " on map    --->" + latitude + " " + longitude);
    displayLocation();

}

public void displayLocation() {
    try {
        GPSTracker gps = new GPSTracker(MainActivity.this);
        if (gps.canGetLocation()) {
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            Toast.makeText(getApplicationContext(), "Latitude: " + latitude + " Longitude: " + longitude, Toast.LENGTH_LONG).show();
            final LatLng loc = new LatLng(latitude, longitude);
            Marker ham = googleMa.addMarker(new MarkerOptions().position(loc).title("This is Me").icon(BitmapDescriptorFactory.fromResource(R.drawable.greenpointer)));
            googleMa.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        }
    } catch (Exception e) {
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.i("aaaaaaaa", "Connection failed: ConnectionResult.getErrorCode() = "
            + result.getErrorCode());
}

@Override
public void onConnected(Bundle arg0) {
    startLocationUpdates();
}

@Override
public void onConnectionSuspended(int arg0) {
    mGoogleApiClient.connect();
}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    Log.d("aaaaaaaa===>", "" + String.valueOf(location.getLatitude()) + "\n" + String.valueOf(location.getLongitude()));
    Toast.makeText(getApplicationContext(), "Location changed!",
            Toast.LENGTH_SHORT).show();
    displayLocation();
}

private boolean checkPlayServices() {

    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();

    int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(this);

    if (resultCode != ConnectionResult.SUCCESS) {
        if (googleApiAvailability.isUserResolvableError(resultCode)) {
            googleApiAvailability.getErrorDialog(this, resultCode,
                    1000).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "This device is not supported.", Toast.LENGTH_LONG)
                    .show();
            finish();
        }
        return false;
    }
    return true;
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();

    mGoogleApiClient.connect();

    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(100);
    mLocationRequest.setFastestInterval(500);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult locationSettingsResult) {

            final Status status = locationSettingsResult.getStatus();

            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    try {
                        status.startResolutionForResult(MainActivity.this, 2000);

                    } catch (IntentSender.SendIntentException e) {
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    break;
            }
        }
    });
}

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000); // 10 sec
    mLocationRequest.setFastestInterval(5000); // 5 sec
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(10); // 10 meters
}

protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    stopLocationUpdates();
}

}

1个回答

2
onLocationChanged 被触发后,您需要从 location 实例中获取 latitudelongitude,而不是从 gps 中获取(我不知道 GPSTracker 是什么,没有代码,但肯定不会给您更新的经纬度信息)。
@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    // use latitude and longitude given by 
    // location.getLatitude(), location.getLongitude()
    // for updated location marker
    Log.d("aaaaaaaa===>", "" + location.getLatitude() + "\n" + location.getLongitude());
   // displayLocation();

    // to remove old markers
    googleMa.clear();
    final LatLng loc = new LatLng(location.getLongitude(), location.getLongitude());

    Marker ham = googleMa.addMarker(new MarkerOptions().position(loc).title("This is Me").icon(BitmapDescriptorFactory.fromResource(R.drawable.greenpointer)));
    googleMa.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
}

1
我在位置改变函数中使用了标记,但是在位置改变调用时会得到多个标记。 - webaddicted
1
@DeepakSharma噢,你需要清除旧的标记。我猜测有一个名为googleMa.clear()的函数或者类似的东西。在添加标记之前调用这个函数。 - Pavneet_Singh
我很高兴能够帮助。 - Pavneet_Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接