Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.78 KB | None | 0 0
  1. public class MainActivity extends AppCompatActivity
  2. implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
  3. GoogleApiClient.OnConnectionFailedListener,LocationListener{
  4. private GoogleMap mMap;
  5. private GoogleApiClient mGoogleApiClient;
  6. protected LocationRequest mLocationRequest;
  7. protected Location mLastLocation;
  8. protected DrawerLayout drawer;
  9. private Marker mCurrLocationMarker;
  10. protected double latitude;
  11. protected double longitude;
  12. private ProgressDialog loading;
  13. protected Marker locationMarker;
  14. private String TAG = MainActivity.class.getSimpleName();
  15.  
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_eve_app__main_2016);
  20. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  21. checkLocationPermission();
  22. }
  23. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  24. mapFragment.getMapAsync(this);
  25. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  26.  
  27. setSupportActionBar(toolbar);
  28.  
  29. FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
  30. fab.setOnClickListener(new View.OnClickListener() {
  31. @Override
  32. public void onClick(View view) {
  33. Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
  34. .setAction("Action", null).show();
  35. }
  36. });
  37.  
  38. drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  39. ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
  40. this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
  41. drawer.addDrawerListener(toggle);
  42. toggle.syncState();
  43.  
  44. NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
  45. navigationView.setNavigationItemSelectedListener(this);
  46. }
  47. protected void displayOnMapLatLang(double latitude,double longitude){
  48. RequestQueue mRequestQueue = AppController.getInstance().getRequestQueue();
  49. mRequestQueue.start();
  50. loading = ProgressDialog.show(this,"Getting nearest places ...","",false,false);
  51. loading.setCancelable(false);
  52. String url = AppConfig.URL_RetrieveCoordinates+"?"+"latitude="+latitude+"&"+"longitude="+longitude;
  53. JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
  54. (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
  55. @Override
  56. public void onResponse(JSONArray response) {
  57. // do something with response
  58. loading.dismiss();
  59. showOnMap(response);
  60. }
  61. }, new Response.ErrorListener() {
  62.  
  63. @Override
  64. public void onErrorResponse(VolleyError error) {
  65. // handle error
  66. if (error instanceof TimeoutError || error instanceof NoConnectionError) {
  67. Toast.makeText(getApplicationContext(),
  68. getApplicationContext().getString(R.string.error_network_timeout),
  69. Toast.LENGTH_LONG).show();
  70. } else if (error instanceof AuthFailureError) {
  71. Toast.makeText(getApplicationContext(),
  72. getApplicationContext().getString(R.string.auth_fail_error),
  73. Toast.LENGTH_LONG).show();
  74. } else if (error instanceof ServerError) {
  75. Toast.makeText(getApplicationContext(),
  76. getApplicationContext().getString(R.string.server_error),
  77. Toast.LENGTH_LONG).show();
  78. } else if (error instanceof NetworkError) {
  79. Toast.makeText(getApplicationContext(),
  80. getApplicationContext().getString(R.string.network_error),
  81. Toast.LENGTH_LONG).show();
  82. } else if (error instanceof ParseError) {
  83. Toast.makeText(getApplicationContext(),
  84. getApplicationContext().getString(R.string.Parse_Error),
  85. Toast.LENGTH_LONG).show();
  86. }
  87. }
  88. });
  89. AppController.getInstance().addToRequestQueue(jsonArrayRequest);
  90. }
  91.  
  92. private void showOnMap(JSONArray response){
  93. String[] uniqueID = new String[response.length()];
  94. String[] PlacesLatitude = new String[response.length()];
  95. String[] PlacesLongitude = new String[response.length()];
  96. String[] Distance = new String[response.length()];
  97. try{
  98. for(int i = 0 ; i < response.length() ; i++){
  99. JSONObject jsonObject = response.getJSONObject(i);
  100. uniqueID[i] = jsonObject.getString("unique_ID");
  101. PlacesLatitude[i] = jsonObject.getString("PlacesLatitude");
  102. PlacesLongitude[i] = jsonObject.getString("PlacesLongitude");
  103. Distance[i] = jsonObject.getString("distance");
  104. }
  105. displayOnMap(uniqueID,PlacesLatitude,PlacesLongitude,Distance);
  106. }catch (JSONException ex){
  107. ex.printStackTrace();
  108. }
  109. }
  110.  
  111. private void displayOnMap(final String uniqueID[], final String PlacesLatitude[], final String PlacesLongitude[],
  112. final String[] Distance) {
  113. final HashMap<Marker,String> storeUniqueId = new HashMap<>();
  114. for(int i = 0 ; i < uniqueID.length ; i++){
  115. if(i==0) ////FOR ANIMATING THE CAMERA FOCUS FIRST TIME ON THE GOOGLE MAP
  116. {
  117. CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(Double.parseDouble(PlacesLatitude[i]),
  118. Double.parseDouble(PlacesLongitude[i]))).zoom(9).build();
  119. mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
  120. storeUniqueId.put(locationMarker,uniqueID[i]);
  121. }
  122. locationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(PlacesLatitude[i]),
  123. Double.parseDouble(PlacesLongitude[i])))
  124. .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
  125. .title(uniqueID[i]+" "+Double.parseDouble(PlacesLatitude[i])+
  126. " "+Double.parseDouble(PlacesLongitude[i])+" "+Double.parseDouble(Distance[i])
  127. ));
  128. storeUniqueId.put(locationMarker,uniqueID[i]);
  129. }
  130. mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
  131. {
  132. @Override
  133. public boolean onMarkerClick(Marker marker) {
  134. String uniqueID = storeUniqueId.get(marker);
  135. Intent intent = new Intent(MainActivity.this,DisplayHallInformationActivity.class);
  136. intent.putExtra("uniqueID",uniqueID);
  137. startActivity(intent);
  138. return false;
  139. }
  140. });
  141. }
  142.  
  143. @Override
  144. public void onBackPressed() {
  145. DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  146. if (drawer.isDrawerOpen(GravityCompat.START)) {
  147. drawer.closeDrawer(GravityCompat.START);
  148. } else {
  149. super.onBackPressed();
  150. }
  151. }
  152.  
  153. @Override
  154. public boolean onCreateOptionsMenu(Menu menu) {
  155. // Inflate the menu; this adds items to the action bar if it is present.
  156. getMenuInflater().inflate(R.menu.eve_app__main__activity2016, menu);
  157. return true;
  158. }
  159.  
  160. @Override
  161. public boolean onOptionsItemSelected(MenuItem item) {
  162. // Handle action bar item clicks here. The action bar will
  163. // automatically handle clicks on the Home/Up button, so long
  164. // as you specify a parent activity in AndroidManifest.xml.
  165. int id = item.getItemId();
  166.  
  167. //noinspection SimplifiableIfStatement
  168. if (id == R.id.action_settings) {
  169. return true;
  170. }
  171. if(id == R.id.hall_person){
  172. Intent intent = new Intent(this,LogIn_Member_Source.class);
  173. startActivity(intent);
  174. }
  175. return super.onOptionsItemSelected(item);
  176. }
  177.  
  178. @SuppressWarnings("StatementWithEmptyBody")
  179. @Override
  180. public boolean onNavigationItemSelected(@NonNull MenuItem item) {
  181. // Handle navigation view item clicks here.
  182. int id = item.getItemId();
  183.  
  184. if (id == R.id.nav_camera) {
  185. // Handle the camera action
  186. } else if (id == R.id.nav_gallery) {
  187.  
  188. } else if (id == R.id.nav_slideshow) {
  189.  
  190. } else if (id == R.id.nav_manage) {
  191.  
  192. } else if (id == R.id.nav_share) {
  193.  
  194. } else if (id == R.id.nav_send) {
  195.  
  196. }
  197.  
  198. DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  199. drawer.closeDrawer(GravityCompat.START);
  200. return true;
  201. }
  202.  
  203. @Override
  204. public void onMapReady(GoogleMap googleMap) {
  205. mMap = googleMap;
  206. mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
  207. //Initialize google play service
  208. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  209. if (ContextCompat.checkSelfPermission(this,
  210. Manifest.permission.ACCESS_FINE_LOCATION)
  211. == PackageManager.PERMISSION_GRANTED) {
  212. buildGoogleApiClient();
  213. mMap.setMyLocationEnabled(true);
  214. buildingLocationSetting();
  215. }
  216. }
  217. else {
  218. buildGoogleApiClient();
  219. mMap.setMyLocationEnabled(true);
  220. buildingLocationSetting();
  221. }
  222. }
  223.  
  224. private void buildingLocationSetting() {
  225. LocationRequest locationRequest = LocationRequest.create();
  226. locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  227. locationRequest.setInterval(10000);
  228. locationRequest.setFastestInterval(10000 / 2);
  229.  
  230. LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
  231. builder.setAlwaysShow(true);
  232. PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
  233. result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
  234. @Override
  235. public void onResult(LocationSettingsResult result) {
  236. final Status status = result.getStatus();
  237. switch (status.getStatusCode()) {
  238. case LocationSettingsStatusCodes.SUCCESS:
  239. Log.i(TAG, "All location settings are satisfied.");
  240. break;
  241. case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
  242. Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
  243.  
  244. try {
  245. // Show the dialog by calling startResolutionForResult(), and check the result
  246. // in onActivityResult().
  247. status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
  248. } catch (IntentSender.SendIntentException e) {
  249. Log.i(TAG, "PendingIntent unable to execute request.");
  250. }
  251. break;
  252. case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
  253. Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
  254. break;
  255. }
  256. }
  257. });
  258. }
  259.  
  260. protected synchronized void buildGoogleApiClient() {
  261. mGoogleApiClient = new GoogleApiClient.Builder(this)
  262. .addConnectionCallbacks(this)
  263. .addOnConnectionFailedListener(this)
  264. .addApi(LocationServices.API)
  265. .build();
  266. mGoogleApiClient.connect();
  267. }
  268. /*
  269. @Override
  270. protected void onPause() {
  271. super.onPause();
  272. if (mGoogleApiClient.isConnected()) {
  273. LocationServices.FusedLocationApi.removeLocationUpdates(
  274. mGoogleApiClient, this);
  275. }
  276. }
  277. */
  278. @Override
  279. public void onConnected(@Nullable Bundle bundle) {
  280. mLocationRequest = new LocationRequest();
  281. mLocationRequest.setInterval(1000);
  282. mLocationRequest.setFastestInterval(1000);
  283. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
  284. if (ContextCompat.checkSelfPermission(this,
  285. Manifest.permission.ACCESS_FINE_LOCATION)
  286. == PackageManager.PERMISSION_GRANTED) {
  287. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
  288. }
  289.  
  290. }
  291.  
  292. @Override
  293. public void onConnectionSuspended(int i) {
  294.  
  295. }
  296.  
  297. @Override
  298. public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  299.  
  300. }
  301.  
  302. @Override
  303. public void onLocationChanged(Location location) {
  304. mLastLocation = location;
  305. if (mCurrLocationMarker != null) {
  306. mCurrLocationMarker.remove();
  307. }
  308. //Place current location marker
  309. /*LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
  310. MarkerOptions markerOptions = new MarkerOptions();
  311. markerOptions.position(latLng);
  312. markerOptions.title("Current Position");
  313. markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
  314. mCurrLocationMarker = mMap.addMarker(markerOptions);
  315.  
  316. //move map camera
  317. mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
  318. mMap.animateCamera(CameraUpdateFactory.zoomTo(11));*/
  319. latitude = location.getLatitude();
  320. longitude = location.getLongitude();
  321. //stop location updates
  322. if (mGoogleApiClient != null) {
  323. LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
  324. }
  325. displayOnMapLatLang(latitude,longitude);
  326. }
  327. public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
  328. public boolean checkLocationPermission(){
  329. if (ContextCompat.checkSelfPermission(this,
  330. Manifest.permission.ACCESS_FINE_LOCATION)
  331. != PackageManager.PERMISSION_GRANTED) {
  332.  
  333. // Asking user if explanation is needed
  334. if (ActivityCompat.shouldShowRequestPermissionRationale(this,
  335. Manifest.permission.ACCESS_FINE_LOCATION)) {
  336.  
  337. // Show an explanation to the user *asynchronously* -- don't block
  338. // this thread waiting for the user's response! After the user
  339. // sees the explanation, try again to request the permission.
  340.  
  341. //Prompt the user once explanation has been shown
  342. ActivityCompat.requestPermissions(this,
  343. new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
  344. MY_PERMISSIONS_REQUEST_LOCATION);
  345.  
  346.  
  347. } else {
  348. // No explanation needed, we can request the permission.
  349. ActivityCompat.requestPermissions(this,
  350. new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
  351. MY_PERMISSIONS_REQUEST_LOCATION);
  352. }
  353. return false;
  354. } else {
  355. return true;
  356. }
  357. }
  358. @Override
  359. public void onRequestPermissionsResult(int requestCode,@NonNull String permissions[], @NonNull int[] grantResults) {
  360. switch (requestCode) {
  361. case MY_PERMISSIONS_REQUEST_LOCATION: {
  362. // If request is cancelled, the result arrays are empty.
  363. if (grantResults.length > 0
  364. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  365.  
  366. // permission was granted. Do the
  367. // contacts-related task you need to do.
  368. if (ContextCompat.checkSelfPermission(this,
  369. Manifest.permission.ACCESS_FINE_LOCATION)
  370. == PackageManager.PERMISSION_GRANTED) {
  371.  
  372. if (mGoogleApiClient == null) {
  373. buildGoogleApiClient();
  374. }
  375. mMap.setMyLocationEnabled(true);
  376. }
  377.  
  378. } else {
  379.  
  380. // Permission denied, Disable the functionality that depends on this permission.
  381. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
  382. }
  383. }
  384. }
  385. }
  386. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement