Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package location.locationtest;
- import android.graphics.Point;
- import android.location.Location;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.SystemClock;
- import android.support.v7.app.AppCompatActivity;
- import android.util.Log;
- import android.view.View;
- import android.view.animation.Interpolator;
- import android.view.animation.LinearInterpolator;
- import android.widget.Button;
- import android.widget.Toast;
- import com.google.android.gms.common.ConnectionResult;
- import com.google.android.gms.common.GooglePlayServicesUtil;
- import com.google.android.gms.common.api.GoogleApiClient;
- import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
- import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
- import com.google.android.gms.location.LocationListener;
- import com.google.android.gms.location.LocationRequest;
- 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.Projection;
- 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 MainActivity extends AppCompatActivity implements ConnectionCallbacks,
- OnConnectionFailedListener, LocationListener, OnMapReadyCallback {
- // LogCat tag
- private static final String TAG = MainActivity.class.getSimpleName();
- private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
- private Location mLastLocation;
- // Google client to interact with Google API
- private GoogleApiClient mGoogleApiClient;
- // boolean flag to toggle periodic location updates
- private boolean mRequestingLocationUpdates = false;
- private LocationRequest mLocationRequest;
- // Location updates intervals in sec
- private static int UPDATE_INTERVAL = 10000; // 10 sec
- private static int FASTEST_INTERVAL = 5000; // 5 sec
- private static int DISPLACEMENT = 10; // 10 meters
- // UI elements
- //private TextView lblLocation;
- // private Button btnShowLocation, btnStartLocationUpdates;
- private Button btnStartLocationUpdates;
- private GoogleMap mMap;
- private LatLng latLng;
- private Marker marker;
- private int i = 0;
- @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);
- // lblLocation = (TextView) findViewById(R.id.lblLocation);
- //btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
- btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
- // First we need to check availability of play services
- if (checkPlayServices()) {
- // Building the GoogleApi client
- buildGoogleApiClient();
- createLocationRequest();
- }
- /* // Show location button click listener
- btnShowLocation.setOnClickListener(new lView.OnClickListener() {
- @Override
- public void onClick(View v) {
- displayLocation();
- }
- });*/
- // Toggling the periodic location updates
- btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- togglePeriodicLocationUpdates();
- }
- });
- }
- /**
- * Manipulates the map once available.
- * This callback is triggered when the map is ready to be used.
- * This is where we can add markers or lines, add listeners or move the camera. In this case,
- * we just add a marker near Sydney, Australia.
- * If Google Play services is not installed on the device, the user will be prompted to install
- * it inside the SupportMapFragment. This method will only be triggered once the user has
- * installed Google Play services and returned to the app.
- */
- @Override
- public void onMapReady(GoogleMap googleMap) {
- mMap = googleMap;
- }
- @Override
- protected void onStart() {
- super.onStart();
- if (mGoogleApiClient != null) {
- mGoogleApiClient.connect();
- }
- }
- @Override
- protected void onResume() {
- super.onResume();
- checkPlayServices();
- // Resuming the periodic location updates
- if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
- startLocationUpdates();
- }
- }
- @Override
- protected void onStop() {
- super.onStop();
- if (mGoogleApiClient.isConnected()) {
- mGoogleApiClient.disconnect();
- }
- }
- @Override
- protected void onPause() {
- super.onPause();
- stopLocationUpdates();
- }
- /**
- * Method to display the location on UI
- */
- private void displayLocation() {
- /* mLastLocation = LocationServices.FusedLocationApi
- .getLastLocation(mGoogleApiClient);*/
- if (mLastLocation != null && mMap != null) {
- Toast.makeText(this, "Moved", Toast.LENGTH_LONG).show();
- latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
- // Showing the current location in Google Map
- mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
- // Zoom in the Google Map
- mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
- if (marker == null) {
- marker = mMap.addMarker(new MarkerOptions()
- .position(latLng));
- }
- animateMarker(marker, new LatLng(10.0152, 76.3294), false);
- } else {
- Toast.makeText(this, "Enable location updates.", Toast.LENGTH_LONG).show();
- }
- }
- /**
- * Method to toggle periodic location updates
- */
- private void togglePeriodicLocationUpdates() {
- if (!mRequestingLocationUpdates) {
- // Changing the button text
- btnStartLocationUpdates
- .setText(getString(R.string.btn_stop_location_updates));
- mRequestingLocationUpdates = true;
- // Starting the location updates
- startLocationUpdates();
- Log.d(TAG, "Periodic location updates started!");
- } else {
- // Changing the button text
- btnStartLocationUpdates
- .setText(getString(R.string.btn_start_location_updates));
- mRequestingLocationUpdates = false;
- // Stopping the location updates
- stopLocationUpdates();
- Log.d(TAG, "Periodic location updates stopped!");
- }
- }
- /**
- * Creating google api client object
- */
- protected synchronized void buildGoogleApiClient() {
- mGoogleApiClient = new GoogleApiClient.Builder(this)
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(LocationServices.API).build();
- }
- /**
- * Creating location request object
- */
- protected void createLocationRequest() {
- mLocationRequest = new LocationRequest();
- mLocationRequest.setInterval(UPDATE_INTERVAL);
- mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
- mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
- mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
- }
- /**
- * Method to verify google play services on the device
- */
- private boolean checkPlayServices() {
- int resultCode = GooglePlayServicesUtil
- .isGooglePlayServicesAvailable(this);
- if (resultCode != ConnectionResult.SUCCESS) {
- if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
- GooglePlayServicesUtil.getErrorDialog(resultCode, this,
- PLAY_SERVICES_RESOLUTION_REQUEST).show();
- } else {
- Toast.makeText(getApplicationContext(),
- "This device is not supported.", Toast.LENGTH_LONG)
- .show();
- finish();
- }
- return false;
- }
- return true;
- }
- /**
- * Starting the location updates
- */
- protected void startLocationUpdates() {
- LocationServices.FusedLocationApi.requestLocationUpdates(
- mGoogleApiClient, mLocationRequest, this);
- }
- /**
- * Stopping location updates
- */
- protected void stopLocationUpdates() {
- LocationServices.FusedLocationApi.removeLocationUpdates(
- mGoogleApiClient, this);
- }
- /**
- * Google api callback methods
- */
- @Override
- public void onConnectionFailed(ConnectionResult result) {
- Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
- + result.getErrorCode());
- }
- @Override
- public void onConnected(Bundle arg0) {
- // Once connected with google api, get the location
- displayLocation();
- if (mRequestingLocationUpdates) {
- startLocationUpdates();
- }
- }
- @Override
- public void onConnectionSuspended(int arg0) {
- mGoogleApiClient.connect();
- }
- @Override
- public void onLocationChanged(Location location) {
- // Assign the new location
- mLastLocation = location;
- Toast.makeText(getApplicationContext(), "Location changed!",
- Toast.LENGTH_SHORT).show();
- // Displaying the new location on UI
- displayLocation();
- }
- private void animateMarker(final Marker marker, final LatLng toPosition,
- final boolean hideMarker) {
- final Handler handler = new Handler();
- final long start = SystemClock.uptimeMillis();
- Projection proj = mMap.getProjection();
- Point startPoint = proj.toScreenLocation(marker.getPosition());
- final LatLng startLatLng = proj.fromScreenLocation(startPoint);
- final long duration = 1000;
- final Interpolator interpolator = new LinearInterpolator();
- handler.post(new Runnable() {
- @Override
- public void run() {
- long elapsed = SystemClock.uptimeMillis() - start;
- float t = interpolator.getInterpolation((float) elapsed
- / duration);
- double lng = t * toPosition.longitude + (1 - t)
- * startLatLng.longitude;
- double lat = t * toPosition.latitude + (1 - t)
- * startLatLng.latitude;
- marker.setPosition(new LatLng(lat, lng));
- if (t < 1.0) {
- // Post again 16ms later.
- handler.postDelayed(this, 16);
- } else {
- if (hideMarker) {
- marker.setVisible(false);
- } else {
- marker.setVisible(true);
- }
- }
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement