Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainActivity extends AppCompatActivity
- implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
- GoogleApiClient.OnConnectionFailedListener,LocationListener{
- private GoogleMap mMap;
- private GoogleApiClient mGoogleApiClient;
- protected LocationRequest mLocationRequest;
- protected Location mLastLocation;
- protected DrawerLayout drawer;
- private Marker mCurrLocationMarker;
- protected double latitude;
- protected double longitude;
- private ProgressDialog loading;
- protected Marker locationMarker;
- private String TAG = MainActivity.class.getSimpleName();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_eve_app__main_2016);
- if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- checkLocationPermission();
- }
- SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
- mapFragment.getMapAsync(this);
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
- fab.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
- .setAction("Action", null).show();
- }
- });
- drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
- ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
- this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
- drawer.addDrawerListener(toggle);
- toggle.syncState();
- NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
- navigationView.setNavigationItemSelectedListener(this);
- }
- protected void displayOnMapLatLang(double latitude,double longitude){
- RequestQueue mRequestQueue = AppController.getInstance().getRequestQueue();
- mRequestQueue.start();
- loading = ProgressDialog.show(this,"Getting nearest places ...","",false,false);
- loading.setCancelable(false);
- String url = AppConfig.URL_RetrieveCoordinates+"?"+"latitude="+latitude+"&"+"longitude="+longitude;
- JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
- (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
- @Override
- public void onResponse(JSONArray response) {
- // do something with response
- loading.dismiss();
- showOnMap(response);
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- // handle error
- if (error instanceof TimeoutError || error instanceof NoConnectionError) {
- Toast.makeText(getApplicationContext(),
- getApplicationContext().getString(R.string.error_network_timeout),
- Toast.LENGTH_LONG).show();
- } else if (error instanceof AuthFailureError) {
- Toast.makeText(getApplicationContext(),
- getApplicationContext().getString(R.string.auth_fail_error),
- Toast.LENGTH_LONG).show();
- } else if (error instanceof ServerError) {
- Toast.makeText(getApplicationContext(),
- getApplicationContext().getString(R.string.server_error),
- Toast.LENGTH_LONG).show();
- } else if (error instanceof NetworkError) {
- Toast.makeText(getApplicationContext(),
- getApplicationContext().getString(R.string.network_error),
- Toast.LENGTH_LONG).show();
- } else if (error instanceof ParseError) {
- Toast.makeText(getApplicationContext(),
- getApplicationContext().getString(R.string.Parse_Error),
- Toast.LENGTH_LONG).show();
- }
- }
- });
- AppController.getInstance().addToRequestQueue(jsonArrayRequest);
- }
- private void showOnMap(JSONArray response){
- String[] uniqueID = new String[response.length()];
- String[] PlacesLatitude = new String[response.length()];
- String[] PlacesLongitude = new String[response.length()];
- String[] Distance = new String[response.length()];
- try{
- for(int i = 0 ; i < response.length() ; i++){
- JSONObject jsonObject = response.getJSONObject(i);
- uniqueID[i] = jsonObject.getString("unique_ID");
- PlacesLatitude[i] = jsonObject.getString("PlacesLatitude");
- PlacesLongitude[i] = jsonObject.getString("PlacesLongitude");
- Distance[i] = jsonObject.getString("distance");
- }
- displayOnMap(uniqueID,PlacesLatitude,PlacesLongitude,Distance);
- }catch (JSONException ex){
- ex.printStackTrace();
- }
- }
- private void displayOnMap(final String uniqueID[], final String PlacesLatitude[], final String PlacesLongitude[],
- final String[] Distance) {
- final HashMap<Marker,String> storeUniqueId = new HashMap<>();
- for(int i = 0 ; i < uniqueID.length ; i++){
- if(i==0) ////FOR ANIMATING THE CAMERA FOCUS FIRST TIME ON THE GOOGLE MAP
- {
- CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(Double.parseDouble(PlacesLatitude[i]),
- Double.parseDouble(PlacesLongitude[i]))).zoom(9).build();
- mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
- storeUniqueId.put(locationMarker,uniqueID[i]);
- }
- locationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(PlacesLatitude[i]),
- Double.parseDouble(PlacesLongitude[i])))
- .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
- .title(uniqueID[i]+" "+Double.parseDouble(PlacesLatitude[i])+
- " "+Double.parseDouble(PlacesLongitude[i])+" "+Double.parseDouble(Distance[i])
- ));
- storeUniqueId.put(locationMarker,uniqueID[i]);
- }
- mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
- {
- @Override
- public boolean onMarkerClick(Marker marker) {
- String uniqueID = storeUniqueId.get(marker);
- Intent intent = new Intent(MainActivity.this,DisplayHallInformationActivity.class);
- intent.putExtra("uniqueID",uniqueID);
- startActivity(intent);
- return false;
- }
- });
- }
- @Override
- public void onBackPressed() {
- DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
- if (drawer.isDrawerOpen(GravityCompat.START)) {
- drawer.closeDrawer(GravityCompat.START);
- } else {
- super.onBackPressed();
- }
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.eve_app__main__activity2016, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- //noinspection SimplifiableIfStatement
- if (id == R.id.action_settings) {
- return true;
- }
- if(id == R.id.hall_person){
- Intent intent = new Intent(this,LogIn_Member_Source.class);
- startActivity(intent);
- }
- return super.onOptionsItemSelected(item);
- }
- @SuppressWarnings("StatementWithEmptyBody")
- @Override
- public boolean onNavigationItemSelected(@NonNull MenuItem item) {
- // Handle navigation view item clicks here.
- int id = item.getItemId();
- if (id == R.id.nav_camera) {
- // Handle the camera action
- } else if (id == R.id.nav_gallery) {
- } else if (id == R.id.nav_slideshow) {
- } else if (id == R.id.nav_manage) {
- } else if (id == R.id.nav_share) {
- } else if (id == R.id.nav_send) {
- }
- DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
- drawer.closeDrawer(GravityCompat.START);
- return true;
- }
- @Override
- public void onMapReady(GoogleMap googleMap) {
- mMap = googleMap;
- mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
- //Initialize google play service
- if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- if (ContextCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_FINE_LOCATION)
- == PackageManager.PERMISSION_GRANTED) {
- buildGoogleApiClient();
- mMap.setMyLocationEnabled(true);
- buildingLocationSetting();
- }
- }
- else {
- buildGoogleApiClient();
- mMap.setMyLocationEnabled(true);
- buildingLocationSetting();
- }
- }
- private void buildingLocationSetting() {
- LocationRequest locationRequest = LocationRequest.create();
- locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
- locationRequest.setInterval(10000);
- locationRequest.setFastestInterval(10000 / 2);
- LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
- builder.setAlwaysShow(true);
- PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
- result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
- @Override
- public void onResult(LocationSettingsResult result) {
- final Status status = result.getStatus();
- switch (status.getStatusCode()) {
- case LocationSettingsStatusCodes.SUCCESS:
- Log.i(TAG, "All location settings are satisfied.");
- break;
- case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
- Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
- try {
- // Show the dialog by calling startResolutionForResult(), and check the result
- // in onActivityResult().
- status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
- } catch (IntentSender.SendIntentException e) {
- Log.i(TAG, "PendingIntent unable to execute request.");
- }
- break;
- case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
- Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
- break;
- }
- }
- });
- }
- protected synchronized void buildGoogleApiClient() {
- mGoogleApiClient = new GoogleApiClient.Builder(this)
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(LocationServices.API)
- .build();
- mGoogleApiClient.connect();
- }
- /*
- @Override
- protected void onPause() {
- super.onPause();
- if (mGoogleApiClient.isConnected()) {
- LocationServices.FusedLocationApi.removeLocationUpdates(
- mGoogleApiClient, this);
- }
- }
- */
- @Override
- public void onConnected(@Nullable Bundle bundle) {
- mLocationRequest = new LocationRequest();
- mLocationRequest.setInterval(1000);
- mLocationRequest.setFastestInterval(1000);
- mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
- if (ContextCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_FINE_LOCATION)
- == PackageManager.PERMISSION_GRANTED) {
- LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
- }
- }
- @Override
- public void onConnectionSuspended(int i) {
- }
- @Override
- public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
- }
- @Override
- public void onLocationChanged(Location location) {
- mLastLocation = location;
- if (mCurrLocationMarker != null) {
- mCurrLocationMarker.remove();
- }
- //Place current location marker
- /*LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
- MarkerOptions markerOptions = new MarkerOptions();
- markerOptions.position(latLng);
- markerOptions.title("Current Position");
- markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
- mCurrLocationMarker = mMap.addMarker(markerOptions);
- //move map camera
- mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
- mMap.animateCamera(CameraUpdateFactory.zoomTo(11));*/
- latitude = location.getLatitude();
- longitude = location.getLongitude();
- //stop location updates
- if (mGoogleApiClient != null) {
- LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
- }
- displayOnMapLatLang(latitude,longitude);
- }
- public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
- public boolean checkLocationPermission(){
- if (ContextCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_FINE_LOCATION)
- != PackageManager.PERMISSION_GRANTED) {
- // Asking user if explanation is needed
- if (ActivityCompat.shouldShowRequestPermissionRationale(this,
- Manifest.permission.ACCESS_FINE_LOCATION)) {
- // Show an explanation to the user *asynchronously* -- don't block
- // this thread waiting for the user's response! After the user
- // sees the explanation, try again to request the permission.
- //Prompt the user once explanation has been shown
- ActivityCompat.requestPermissions(this,
- new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
- MY_PERMISSIONS_REQUEST_LOCATION);
- } else {
- // No explanation needed, we can request the permission.
- ActivityCompat.requestPermissions(this,
- new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
- MY_PERMISSIONS_REQUEST_LOCATION);
- }
- return false;
- } else {
- return true;
- }
- }
- @Override
- public void onRequestPermissionsResult(int requestCode,@NonNull String permissions[], @NonNull int[] grantResults) {
- switch (requestCode) {
- case MY_PERMISSIONS_REQUEST_LOCATION: {
- // If request is cancelled, the result arrays are empty.
- if (grantResults.length > 0
- && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- // permission was granted. Do the
- // contacts-related task you need to do.
- if (ContextCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_FINE_LOCATION)
- == PackageManager.PERMISSION_GRANTED) {
- if (mGoogleApiClient == null) {
- buildGoogleApiClient();
- }
- mMap.setMyLocationEnabled(true);
- }
- } else {
- // Permission denied, Disable the functionality that depends on this permission.
- Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement