Advertisement
Guest User

Untitled

a guest
Nov 3rd, 2015
799
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.56 KB | None | 0 0
  1. package location.locationtest;
  2.  
  3. import android.graphics.Point;
  4. import android.location.Location;
  5. import android.os.Bundle;
  6. import android.os.Handler;
  7. import android.os.SystemClock;
  8. import android.support.v7.app.AppCompatActivity;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.view.animation.Interpolator;
  12. import android.view.animation.LinearInterpolator;
  13. import android.widget.Button;
  14. import android.widget.Toast;
  15.  
  16. import com.google.android.gms.common.ConnectionResult;
  17. import com.google.android.gms.common.GooglePlayServicesUtil;
  18. import com.google.android.gms.common.api.GoogleApiClient;
  19. import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
  20. import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
  21. import com.google.android.gms.location.LocationListener;
  22. import com.google.android.gms.location.LocationRequest;
  23. import com.google.android.gms.location.LocationServices;
  24. import com.google.android.gms.maps.CameraUpdateFactory;
  25. import com.google.android.gms.maps.GoogleMap;
  26. import com.google.android.gms.maps.OnMapReadyCallback;
  27. import com.google.android.gms.maps.Projection;
  28. import com.google.android.gms.maps.SupportMapFragment;
  29. import com.google.android.gms.maps.model.LatLng;
  30. import com.google.android.gms.maps.model.Marker;
  31. import com.google.android.gms.maps.model.MarkerOptions;
  32.  
  33. public class MainActivity extends AppCompatActivity implements ConnectionCallbacks,
  34. OnConnectionFailedListener, LocationListener, OnMapReadyCallback {
  35.  
  36. // LogCat tag
  37. private static final String TAG = MainActivity.class.getSimpleName();
  38.  
  39. private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
  40.  
  41. private Location mLastLocation;
  42.  
  43. // Google client to interact with Google API
  44. private GoogleApiClient mGoogleApiClient;
  45.  
  46. // boolean flag to toggle periodic location updates
  47. private boolean mRequestingLocationUpdates = false;
  48.  
  49. private LocationRequest mLocationRequest;
  50.  
  51. // Location updates intervals in sec
  52. private static int UPDATE_INTERVAL = 10000; // 10 sec
  53. private static int FASTEST_INTERVAL = 5000; // 5 sec
  54. private static int DISPLACEMENT = 10; // 10 meters
  55.  
  56. // UI elements
  57. //private TextView lblLocation;
  58. // private Button btnShowLocation, btnStartLocationUpdates;
  59. private Button btnStartLocationUpdates;
  60. private GoogleMap mMap;
  61. private LatLng latLng;
  62. private Marker marker;
  63. private int i = 0;
  64.  
  65. @Override
  66. protected void onCreate(Bundle savedInstanceState) {
  67. super.onCreate(savedInstanceState);
  68. setContentView(R.layout.activity_maps);
  69. // Obtain the SupportMapFragment and get notified when the map is ready to be used.
  70. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
  71. .findFragmentById(R.id.map);
  72. mapFragment.getMapAsync(this);
  73. // lblLocation = (TextView) findViewById(R.id.lblLocation);
  74. //btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
  75. btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
  76.  
  77. // First we need to check availability of play services
  78. if (checkPlayServices()) {
  79.  
  80. // Building the GoogleApi client
  81. buildGoogleApiClient();
  82.  
  83. createLocationRequest();
  84. }
  85.  
  86. /* // Show location button click listener
  87. btnShowLocation.setOnClickListener(new lView.OnClickListener() {
  88.  
  89. @Override
  90. public void onClick(View v) {
  91. displayLocation();
  92. }
  93. });*/
  94.  
  95. // Toggling the periodic location updates
  96. btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {
  97.  
  98. @Override
  99. public void onClick(View v) {
  100. togglePeriodicLocationUpdates();
  101. }
  102. });
  103.  
  104. }
  105.  
  106. /**
  107. * Manipulates the map once available.
  108. * This callback is triggered when the map is ready to be used.
  109. * This is where we can add markers or lines, add listeners or move the camera. In this case,
  110. * we just add a marker near Sydney, Australia.
  111. * If Google Play services is not installed on the device, the user will be prompted to install
  112. * it inside the SupportMapFragment. This method will only be triggered once the user has
  113. * installed Google Play services and returned to the app.
  114. */
  115. @Override
  116. public void onMapReady(GoogleMap googleMap) {
  117. mMap = googleMap;
  118. }
  119.  
  120. @Override
  121. protected void onStart() {
  122. super.onStart();
  123. if (mGoogleApiClient != null) {
  124. mGoogleApiClient.connect();
  125. }
  126. }
  127.  
  128. @Override
  129. protected void onResume() {
  130. super.onResume();
  131.  
  132. checkPlayServices();
  133.  
  134. // Resuming the periodic location updates
  135. if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
  136. startLocationUpdates();
  137. }
  138. }
  139.  
  140. @Override
  141. protected void onStop() {
  142. super.onStop();
  143. if (mGoogleApiClient.isConnected()) {
  144. mGoogleApiClient.disconnect();
  145. }
  146. }
  147.  
  148. @Override
  149. protected void onPause() {
  150. super.onPause();
  151. stopLocationUpdates();
  152. }
  153.  
  154. /**
  155. * Method to display the location on UI
  156. */
  157. private void displayLocation() {
  158.  
  159. /* mLastLocation = LocationServices.FusedLocationApi
  160. .getLastLocation(mGoogleApiClient);*/
  161.  
  162. if (mLastLocation != null && mMap != null) {
  163. Toast.makeText(this, "Moved", Toast.LENGTH_LONG).show();
  164. latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
  165. // Showing the current location in Google Map
  166. mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
  167. // Zoom in the Google Map
  168. mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
  169. if (marker == null) {
  170. marker = mMap.addMarker(new MarkerOptions()
  171. .position(latLng));
  172. }
  173. animateMarker(marker, new LatLng(10.0152, 76.3294), false);
  174. } else {
  175. Toast.makeText(this, "Enable location updates.", Toast.LENGTH_LONG).show();
  176. }
  177. }
  178.  
  179. /**
  180. * Method to toggle periodic location updates
  181. */
  182. private void togglePeriodicLocationUpdates() {
  183. if (!mRequestingLocationUpdates) {
  184. // Changing the button text
  185. btnStartLocationUpdates
  186. .setText(getString(R.string.btn_stop_location_updates));
  187.  
  188. mRequestingLocationUpdates = true;
  189.  
  190. // Starting the location updates
  191. startLocationUpdates();
  192.  
  193. Log.d(TAG, "Periodic location updates started!");
  194.  
  195. } else {
  196. // Changing the button text
  197. btnStartLocationUpdates
  198. .setText(getString(R.string.btn_start_location_updates));
  199.  
  200. mRequestingLocationUpdates = false;
  201.  
  202. // Stopping the location updates
  203. stopLocationUpdates();
  204.  
  205. Log.d(TAG, "Periodic location updates stopped!");
  206. }
  207. }
  208.  
  209. /**
  210. * Creating google api client object
  211. */
  212. protected synchronized void buildGoogleApiClient() {
  213. mGoogleApiClient = new GoogleApiClient.Builder(this)
  214. .addConnectionCallbacks(this)
  215. .addOnConnectionFailedListener(this)
  216. .addApi(LocationServices.API).build();
  217. }
  218.  
  219. /**
  220. * Creating location request object
  221. */
  222. protected void createLocationRequest() {
  223. mLocationRequest = new LocationRequest();
  224. mLocationRequest.setInterval(UPDATE_INTERVAL);
  225. mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
  226. mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  227. mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
  228. }
  229.  
  230. /**
  231. * Method to verify google play services on the device
  232. */
  233. private boolean checkPlayServices() {
  234. int resultCode = GooglePlayServicesUtil
  235. .isGooglePlayServicesAvailable(this);
  236. if (resultCode != ConnectionResult.SUCCESS) {
  237. if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
  238. GooglePlayServicesUtil.getErrorDialog(resultCode, this,
  239. PLAY_SERVICES_RESOLUTION_REQUEST).show();
  240. } else {
  241. Toast.makeText(getApplicationContext(),
  242. "This device is not supported.", Toast.LENGTH_LONG)
  243. .show();
  244. finish();
  245. }
  246. return false;
  247. }
  248. return true;
  249. }
  250.  
  251. /**
  252. * Starting the location updates
  253. */
  254. protected void startLocationUpdates() {
  255.  
  256. LocationServices.FusedLocationApi.requestLocationUpdates(
  257. mGoogleApiClient, mLocationRequest, this);
  258.  
  259. }
  260.  
  261. /**
  262. * Stopping location updates
  263. */
  264. protected void stopLocationUpdates() {
  265. LocationServices.FusedLocationApi.removeLocationUpdates(
  266. mGoogleApiClient, this);
  267. }
  268.  
  269. /**
  270. * Google api callback methods
  271. */
  272. @Override
  273. public void onConnectionFailed(ConnectionResult result) {
  274. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
  275. + result.getErrorCode());
  276. }
  277.  
  278. @Override
  279. public void onConnected(Bundle arg0) {
  280.  
  281. // Once connected with google api, get the location
  282. displayLocation();
  283.  
  284. if (mRequestingLocationUpdates) {
  285. startLocationUpdates();
  286. }
  287. }
  288.  
  289. @Override
  290. public void onConnectionSuspended(int arg0) {
  291. mGoogleApiClient.connect();
  292. }
  293.  
  294. @Override
  295. public void onLocationChanged(Location location) {
  296. // Assign the new location
  297. mLastLocation = location;
  298.  
  299. Toast.makeText(getApplicationContext(), "Location changed!",
  300. Toast.LENGTH_SHORT).show();
  301.  
  302. // Displaying the new location on UI
  303. displayLocation();
  304. }
  305.  
  306. private void animateMarker(final Marker marker, final LatLng toPosition,
  307. final boolean hideMarker) {
  308. final Handler handler = new Handler();
  309. final long start = SystemClock.uptimeMillis();
  310. Projection proj = mMap.getProjection();
  311. Point startPoint = proj.toScreenLocation(marker.getPosition());
  312. final LatLng startLatLng = proj.fromScreenLocation(startPoint);
  313. final long duration = 1000;
  314.  
  315. final Interpolator interpolator = new LinearInterpolator();
  316. handler.post(new Runnable() {
  317. @Override
  318. public void run() {
  319. long elapsed = SystemClock.uptimeMillis() - start;
  320. float t = interpolator.getInterpolation((float) elapsed
  321. / duration);
  322. double lng = t * toPosition.longitude + (1 - t)
  323. * startLatLng.longitude;
  324. double lat = t * toPosition.latitude + (1 - t)
  325. * startLatLng.latitude;
  326. marker.setPosition(new LatLng(lat, lng));
  327.  
  328. if (t < 1.0) {
  329. // Post again 16ms later.
  330. handler.postDelayed(this, 16);
  331. } else {
  332. if (hideMarker) {
  333. marker.setVisible(false);
  334. } else {
  335. marker.setVisible(true);
  336. }
  337. }
  338. }
  339. });
  340. }
  341. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement