Guest User

Untitled

a guest
Jul 10th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 26.82 KB | None | 0 0
  1. package clbrain.mapio;
  2.  
  3. import android.Manifest;
  4. import android.content.Context;
  5. import android.content.pm.PackageManager;
  6. import android.graphics.Color;
  7. import android.location.Location;
  8. import android.location.LocationListener;
  9. import android.location.LocationManager;
  10. import android.os.Bundle;
  11. import android.os.Looper;
  12. import android.support.annotation.NonNull;
  13. import android.support.v4.app.ActivityCompat;
  14. import android.support.v4.content.ContextCompat;
  15. import android.support.v7.app.AppCompatActivity;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.widget.Button;
  19. import android.widget.FrameLayout;
  20. import android.widget.TextView;
  21. import android.widget.Toast;
  22.  
  23. import com.google.android.gms.location.FusedLocationProviderClient;
  24. import com.google.android.gms.location.LocationAvailability;
  25. import com.google.android.gms.location.LocationCallback;
  26. import com.google.android.gms.location.LocationRequest;
  27. import com.google.android.gms.location.LocationServices;
  28. import com.google.android.gms.maps.CameraUpdateFactory;
  29. import com.google.android.gms.maps.GoogleMap;
  30. import com.google.android.gms.maps.OnMapReadyCallback;
  31. import com.google.android.gms.maps.SupportMapFragment;
  32. import com.google.android.gms.maps.model.LatLng;
  33. import com.google.android.gms.maps.model.LatLngBounds;
  34. import com.google.android.gms.maps.model.Marker;
  35. import com.google.android.gms.maps.model.MarkerOptions;
  36. import com.google.android.gms.maps.model.Polygon;
  37. import com.google.android.gms.maps.model.PolygonOptions;
  38. import com.google.android.gms.tasks.OnCompleteListener;
  39. import com.google.android.gms.tasks.OnSuccessListener;
  40. import com.google.android.gms.tasks.Task;
  41. import com.google.firebase.auth.FirebaseAuth;
  42. import com.google.firebase.auth.FirebaseUser;
  43. import com.google.android.gms.maps.model.MapStyleOptions;
  44.  
  45. import java.util.ArrayList;
  46. import java.util.List;
  47. import java.util.Timer;
  48. import java.util.TimerTask;
  49. import java.util.TreeMap;
  50. import java.util.TreeSet;
  51.  
  52. import retrofit2.Call;
  53. import retrofit2.Callback;
  54. import retrofit2.Response;
  55.  
  56. public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
  57.  
  58.  
  59.     private GoogleMap mMap;
  60.     private int color;
  61.     //firebase reference
  62.     FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
  63.     //for requests
  64.     TreeSet<SquaresData> allSquaresDataList = new TreeSet<>();
  65.  
  66.     class MyTimerTask extends TimerTask {
  67.         @Override
  68.         public void run() {
  69.             runOnUiThread(new Runnable() {
  70.                 @Override
  71.                 public void run() {
  72.                     sendCoordinates();
  73.                     getFrameData();
  74.                     init();
  75.                     Log.e("print map", polygonTreeMap.toString());
  76.                 }
  77.             });
  78.         }
  79.     }
  80.  
  81.     private Timer mTimer;
  82.     private Toast internetFailure;
  83.     private List<SquaresData> squaresDataList = new ArrayList<>();
  84.  
  85.     // The entry point to the Fused Location Provider.
  86.     private FusedLocationProviderClient mFusedLocationClient;
  87.  
  88.     // A default location (Sydney, Australia) and default zoom to use when location permission is
  89.     // not granted.
  90.     private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
  91.     private static final int DEFAULT_ZOOM = 17;
  92.     private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
  93.     private boolean mLocationPermissionGranted;
  94.  
  95.     // The geographical location where the device is currently located. That is, the last-known
  96.     // location retrieved by the Fused Location Provider.
  97.     private Location mLastKnownLocation;
  98.  
  99.     // Keys for storing activity state.
  100.     private static final String KEY_CAMERA_POSITION = "camera_position";
  101.     private static final String KEY_LOCATION = "location";
  102.  
  103.     //For drawing polylines at the map
  104.     class Coordinates implements Comparable<Coordinates> {
  105.  
  106.         @Override
  107.         public String toString() {
  108.             return vertical_id + "; " + horizontal_id;
  109.         }
  110.  
  111.         Integer vertical_id, horizontal_id;
  112.  
  113.         private Coordinates(Integer vertical_id, Integer horizontal_id) {
  114.             this.vertical_id = vertical_id;
  115.             this.horizontal_id = horizontal_id;
  116.         }
  117.  
  118.         private Coordinates() {
  119.         }
  120.  
  121.         @Override
  122.         public int compareTo(@NonNull Coordinates coordinates) {
  123.             int h1 = coordinates.horizontal_id;
  124.             int v1 = coordinates.vertical_id;
  125.             int h2 = this.horizontal_id;
  126.             int v2 = this.vertical_id;
  127.             if (h1 == h2 && v1 == v2) return 0;
  128.             else if (h1 > h2 || (h1 == h2 && v1 > v2)) return 1;
  129.             else return -1;
  130.         }
  131.     }
  132.  
  133.     TreeMap<Coordinates, Polygon> polygonTreeMap = new TreeMap<>();
  134.     SupportMapFragment mapFragment;
  135.  
  136.     private void getFrameData() {
  137.         FrameData bounds = getBounds();
  138.         Call<SquaresDataList> call = Requests.apiServices.getFrameData(bounds.getLeft_bottom_corner_latitude(),
  139.                 bounds.getLeft_bottom_corner_longitude(), bounds.getRight_top_corner_latitude(), bounds.getRight_top_corner_longitude());
  140.         call.enqueue(new Callback<SquaresDataList>() {
  141.             @Override
  142.             public void onResponse(@NonNull Call<SquaresDataList> call, @NonNull Response<SquaresDataList> response) {
  143.                 if (response.isSuccessful()) {
  144.                     if (response.body() != null) {
  145.                         Log.i("SQUARES", response.body().getSquares().toString() + " ");
  146.                         ArrayList<SquaresData> squaresList = (ArrayList<SquaresData>) response.body().getSquares();
  147.                         for (int i = 0; i < squaresList.size(); i++) {
  148.                             if (allSquaresDataList.contains(squaresList.get(i))) {
  149.                                 squaresList.remove(squaresList.get(i));
  150.                             }
  151.                         }
  152.                         squaresDataList = squaresList;
  153.                         allSquaresDataList.addAll(squaresList);
  154.                     }
  155.                 } else {
  156.                     internetFailure.show();
  157.                 }
  158.             }
  159.  
  160.             @Override
  161.             public void onFailure(@NonNull Call<SquaresDataList> call, @NonNull Throwable t) {
  162.                 t.printStackTrace();
  163.             }
  164.         });
  165.     }
  166.     /**
  167.      * ОТКРЫВАЮЩЕЕСЯ ПРЕДУПРЕЖДЕНИЕ О НЕРАБТАЮЩЕМ МЕТОДЕ
  168.      */
  169.     private void sendDropBomb(){
  170.         Double latitude = 0.0, longitude = 0.0;
  171.         try {
  172.             latitude = mMap.getMyLocation().getLatitude();
  173.             longitude = mMap.getMyLocation().getLongitude();
  174.         } catch (Exception e) {
  175.             try {
  176.                 LocationManager locationManager = (LocationManager)
  177.                         getSystemService(Context.LOCATION_SERVICE);
  178.                 LocationListener locationListener = new MyLocationListener();
  179.                 if (ActivityCompat.checkSelfPermission(this,
  180.                         android.Manifest.permission.ACCESS_FINE_LOCATION)
  181.                         != PackageManager.PERMISSION_GRANTED
  182.                         && ActivityCompat.checkSelfPermission(this,
  183.                         android.Manifest.permission.ACCESS_COARSE_LOCATION)
  184.                         != PackageManager.PERMISSION_GRANTED) {
  185.                     return;
  186.                 }
  187.                 assert locationManager != null;
  188.                 locationManager.requestLocationUpdates(
  189.                         LocationManager.GPS_PROVIDER, 200, 1, locationListener);
  190.                 latitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
  191.                 longitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
  192.                 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 200, 1, locationListener);
  193.                 latitude = (latitude + locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude()) / 2.0;
  194.                 longitude = (longitude + locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude()) / 2.0;
  195.                 locationManager.removeUpdates(locationListener);
  196.             } catch (Exception exp) {
  197.                 Toast.makeText(getApplicationContext(), "Oooops.. we have some problem", Toast.LENGTH_SHORT).show();
  198.                 Toast.makeText(getApplicationContext(), "Sorry!", Toast.LENGTH_SHORT).show();
  199.             }
  200.         }
  201.         Requests.apiServices.sendDropBomb(new SendCoordinates(user.getUid(), latitude, longitude)).enqueue(new Callback<StringStatus>() {
  202.             @Override
  203.             public void onResponse(@NonNull Call<StringStatus> call, @NonNull Response<StringStatus> response) {
  204.                 if (response.isSuccessful()) {
  205.                 } else {
  206.                     Toast.makeText(getApplicationContext(), "Sending coordinates error...", Toast.LENGTH_SHORT).show();
  207.                     Toast.makeText(getApplicationContext(), "Sorry!!!", Toast.LENGTH_SHORT).show();
  208.                     Toast.makeText(getApplicationContext(), "Leave your angry comment in GooglePlay:)", Toast.LENGTH_LONG).show();
  209.                 }
  210.             }
  211.  
  212.             @Override
  213.             public void onFailure(@NonNull Call<StringStatus> call, @NonNull Throwable t) {
  214.                 internetFailure.show();
  215.             }
  216.         });
  217.     }
  218.  
  219.     /**
  220.      * ЗАКРЫВАЮЩЕЕСЯ ПРЕДУПРЕЖДЕНИЕ О НЕРАБТАЮЩЕМ МЕТОДЕ
  221.      */
  222.     private void sendCoordinates() {
  223.         Double latitude = 0.0, longitude = 0.0;
  224.         try {
  225.             SendCoordinates coordinates = getDeviceCoordinates();
  226.             latitude = coordinates.getLatitude();
  227.             longitude = coordinates.getLongitude();
  228.             Log.i("COORD", latitude + "; " + longitude);
  229.         } catch (Exception e) {
  230.             try {
  231.                 latitude = mMap.getMyLocation().getLatitude();
  232.                 longitude = mMap.getMyLocation().getLongitude();
  233.             } catch (Exception j) {
  234.                 try {
  235.                     LocationManager locationManager = (LocationManager)
  236.                             getSystemService(Context.LOCATION_SERVICE);
  237.                     LocationListener locationListener = new MyLocationListener();
  238.                     if (ActivityCompat.checkSelfPermission(this,
  239.                             android.Manifest.permission.ACCESS_FINE_LOCATION)
  240.                             != PackageManager.PERMISSION_GRANTED
  241.                             && ActivityCompat.checkSelfPermission(this,
  242.                             android.Manifest.permission.ACCESS_COARSE_LOCATION)
  243.                             != PackageManager.PERMISSION_GRANTED) {
  244.                         return;
  245.                     }
  246.                     assert locationManager != null;
  247.                     locationManager.requestLocationUpdates(
  248.                             LocationManager.GPS_PROVIDER, 200, 1, locationListener);
  249.                     latitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
  250.                     longitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
  251.                     locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 200, 1, locationListener);
  252.                     latitude = (latitude + locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude()) / 2.0;
  253.                     longitude = (longitude + locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude()) / 2.0;
  254.                     locationManager.removeUpdates(locationListener);
  255.                 } catch (Exception exp) {
  256.                     Toast.makeText(getApplicationContext(), "Oooops.. we have some problem", Toast.LENGTH_SHORT).show();
  257.                     Toast.makeText(getApplicationContext(), "Sorry!", Toast.LENGTH_SHORT).show();
  258.                 }
  259.             }
  260.         }
  261.         Requests.apiServices.sendCoordinates(new SendCoordinates(user.getUid(), latitude, longitude)).enqueue(new Callback<StringStatus>() {
  262.             @Override
  263.             public void onResponse(@NonNull Call<StringStatus> call, @NonNull Response<StringStatus> response) {
  264.                 if (response.isSuccessful()) {
  265.                 } else {
  266.                     Toast.makeText(getApplicationContext(), "Sending coordinates error...", Toast.LENGTH_SHORT).show();
  267.                     Toast.makeText(getApplicationContext(), "Sorry!!!", Toast.LENGTH_SHORT).show();
  268.                     Toast.makeText(getApplicationContext(), "Leave your angry comment in GooglePlay:)", Toast.LENGTH_LONG).show();
  269.                 }
  270.             }
  271.  
  272.             @Override
  273.             public void onFailure(@NonNull Call<StringStatus> call, @NonNull Throwable t) {
  274.                 internetFailure.show();
  275.             }
  276.         });
  277.     }
  278.  
  279.     private void getSquaresData() {
  280.         Call<SquaresDataList> call = Requests.apiServices.getSquaresData();
  281.         call.enqueue(new Callback<SquaresDataList>() {
  282.             @Override
  283.             public void onResponse(@NonNull Call<SquaresDataList> call, @NonNull Response<SquaresDataList> response) {
  284.                 if (response.isSuccessful()) {
  285.                     if (response.body() != null) {
  286.                         Log.i("SQUARES", response.body().getSquares().toString() + " ");
  287.                         ArrayList<SquaresData> squaresList = (ArrayList<SquaresData>) response.body().getSquares();
  288.                         for (int i = 0; i < squaresList.size(); i++) {
  289.                             if (allSquaresDataList.contains(squaresList.get(i))) {
  290.                                 squaresList.remove(squaresList.get(i));
  291.                             }
  292.                         }
  293.                         squaresDataList = squaresList;
  294.                         allSquaresDataList.addAll(squaresList);
  295.                     }
  296.                 } else {
  297.                     internetFailure.show();
  298.                 }
  299.             }
  300.  
  301.             @Override
  302.             public void onFailure(@NonNull Call<SquaresDataList> call, @NonNull Throwable t) {
  303.                 t.printStackTrace();
  304.             }
  305.         });
  306.     }
  307.  
  308.     private void getUserColor() {
  309.         String uid = user.getUid();
  310.         Call<clbrain.mapio.Color> call = Requests.apiServices.getUserColor(uid);
  311.         call.enqueue(new Callback<clbrain.mapio.Color>() {
  312.             @Override
  313.             public void onResponse(@NonNull Call<clbrain.mapio.Color> call,
  314.                                    @NonNull Response<clbrain.mapio.Color> response) {
  315.                 if (response.isSuccessful()) {
  316.                     assert response.body() != null;
  317.                     color = Color.parseColor(response.body().getUser_color());
  318.                     findViewById(R.id.picked_color_view).findViewById(R.id.color).setBackgroundColor(color);
  319.                     Log.e("COLOR", color + "");
  320.                 } else {
  321.                     Toast.makeText(getApplicationContext(), "We can't get your color", Toast.LENGTH_SHORT).show();
  322.                     Toast.makeText(getApplicationContext(), "Sorry!!!", Toast.LENGTH_SHORT).show();
  323.                 }
  324.             }
  325.  
  326.             @Override
  327.             public void onFailure(@NonNull Call<clbrain.mapio.Color> call, @NonNull Throwable t) {
  328.                 t.printStackTrace();
  329.             }
  330.         });
  331.     }
  332.  
  333.     @Override
  334.     protected void onCreate(Bundle savedInstanceState) {
  335.         super.onCreate(savedInstanceState);
  336.         internetFailure = Toast.makeText(getApplicationContext(), "Check your internet connection", Toast.LENGTH_SHORT);
  337.         // Retrieve the content view that renders the map.
  338.         setContentView(R.layout.activity_main);
  339.         // Construct a FusedLocationProviderClient.
  340.         mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
  341.         // Build the map.
  342.         mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  343.         assert mapFragment != null;
  344.         mapFragment.getMapAsync(this);
  345.         // making requests
  346.         getUserColor();
  347.         mTimer = new Timer();
  348.         MyTimerTask timerTask = new MyTimerTask();
  349.         mTimer.schedule(timerTask, 200, 5000);
  350.         Button btn_drop_bomb = findViewById(R.id.drop_bomb);
  351.         btn_drop_bomb.setOnClickListener(new View.OnClickListener() {
  352.             @Override
  353.             public void onClick(View view) {
  354.                     sendDropBomb();
  355.             }
  356.         });
  357.         startLocationUpdates();
  358.     }
  359.  
  360.     @Override
  361.     protected void onSaveInstanceState(Bundle outState) {
  362.         if (mMap != null) {
  363.             super.onSaveInstanceState(outState);
  364.             outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
  365.             outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
  366.         }
  367.     }
  368.  
  369.     /**
  370.      * Manipulates the map when it's available.
  371.      * This callback is triggered when the map is ready to be used.
  372.      */
  373.  
  374.     @Override
  375.     public void onMapReady(GoogleMap map) {
  376.         mMap = map;
  377.         // Use a custom info window adapter to handle multiple lines of text in the
  378.         // info window contents.
  379.         mMap.setMinZoomPreference(17);
  380.         mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
  381.             @Override
  382.             // Return null here, so that getInfoContents() is called next.
  383.             public View getInfoWindow(Marker arg) {
  384.                 return null;
  385.             }
  386.  
  387.             @Override
  388.             public View getInfoContents(Marker marker) {
  389.                 // Inflate the layouts for the info window, title and snippet.
  390.                 View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
  391.                         (FrameLayout) findViewById(R.id.map), false);
  392.  
  393.                 TextView title = infoWindow.findViewById(R.id.title);
  394.                 title.setText(marker.getTitle());
  395.  
  396.                 TextView snippet = infoWindow.findViewById(R.id.snippet);
  397.                 snippet.setText(marker.getSnippet());
  398.  
  399.                 return infoWindow;
  400.             }
  401.         });
  402.  
  403.  
  404.         mMap.setBuildingsEnabled(true);
  405.         mMap.setMapStyle(new MapStyleOptions(getResources()
  406.                 .getString(R.string.style_json)));
  407.         // Prompt the user for permission.
  408.         getLocationPermission();
  409.         // Turn on the My Location layer and the related control on the map.
  410.         updateLocationUI();
  411.         // Get the current location of the device and set the position of the map.
  412.         getDeviceLocation();
  413.     }
  414.  
  415.     /**
  416.      * Gets the current location of the device, and positions the map's camera.
  417.      */
  418.     private LocationCallback mLocationCallback = new LocationCallback();
  419.     private LocationRequest mLocationRequest = new LocationRequest();
  420.  
  421.     private void startLocationUpdates() {
  422.         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  423.             // TODO: Consider calling
  424.             //    ActivityCompat#requestPermissions
  425.             // here to request the missing permissions, and then overriding
  426.             //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
  427.             //                                          int[] grantResults)
  428.             // to handle the case where the user grants the permission. See the documentation
  429.             // for ActivityCompat#requestPermissions for more details.
  430.             return;
  431.         }
  432.         mFusedLocationClient.requestLocationUpdates(mLocationRequest,
  433.                 mLocationCallback, Looper.myLooper());
  434.     }
  435.  
  436.     private SendCoordinates getDeviceCoordinates() {
  437.         final SendCoordinates[] ans = new SendCoordinates[1];
  438.         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  439.                 != PackageManager.PERMISSION_GRANTED
  440.                 && ActivityCompat.checkSelfPermission
  441.                 (this, Manifest.permission.ACCESS_COARSE_LOCATION)
  442.                 != PackageManager.PERMISSION_GRANTED) {
  443.         }
  444.         mFusedLocationClient.getLastLocation()
  445.                 .addOnSuccessListener(this, new OnSuccessListener<Location>() {
  446.                     @Override
  447.                     public void onSuccess(Location location) {
  448.                         if (location != null) {
  449.                             Log.e("COORD", location.getLatitude() + "; " + location.getLongitude());
  450.                             ans[0] = new SendCoordinates(user.getUid(), location.getLatitude(), location.getLongitude());
  451.                         }
  452.                         else {
  453.                             Toast.makeText(getApplicationContext(),
  454.                                     "Turn on your GPS, please:)", Toast.LENGTH_SHORT).show();
  455.                             Toast.makeText(getApplicationContext(),
  456.                                     "Or leave angry comment in GoodlePlay:)", Toast.LENGTH_SHORT).show();
  457.                         }
  458.                     }
  459.                 });
  460.         return ans[0];
  461.     }
  462.  
  463.     private void getDeviceLocation() {
  464.         try {
  465.             if (mLocationPermissionGranted) {
  466.                 Task<Location> locationResult = mFusedLocationClient.getLastLocation();
  467.                 locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
  468.                     @Override
  469.                     public void onComplete(@NonNull Task<Location> task) {
  470.                         if (task.isSuccessful()) {
  471.                             // Set the map's camera position to the current location of the device.
  472.                             mLastKnownLocation = task.getResult();
  473.  
  474.                             mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
  475.                                     new LatLng(mLastKnownLocation.getLatitude(),
  476.                                             mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
  477.                         } else {
  478.                             Log.d("LOC", "Current location is null. Using defaults.");
  479.                             Log.e("LOC", "Exception: %s", task.getException());
  480.                             mMap.moveCamera(CameraUpdateFactory
  481.                                     .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
  482.                             mMap.getUiSettings().setMyLocationButtonEnabled(false);
  483.                         }
  484.                     }
  485.                 });
  486.             }
  487.         } catch (SecurityException e) {
  488.             Log.e("Exception: %s", e.getMessage());
  489.         }
  490.     }
  491.  
  492.     private void getLocationPermission() {
  493.         if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
  494.                 android.Manifest.permission.ACCESS_FINE_LOCATION)
  495.                 == PackageManager.PERMISSION_GRANTED) {
  496.             mLocationPermissionGranted = true;
  497.         } else {
  498.             ActivityCompat.requestPermissions(this,
  499.                     new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
  500.                     PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
  501.         }
  502.     }
  503.  
  504.     @Override
  505.     public void onRequestPermissionsResult(int requestCode,
  506.                                            @NonNull String permissions[],
  507.                                            @NonNull int[] grantResults) {
  508.         mLocationPermissionGranted = false;
  509.         switch (requestCode) {
  510.             case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
  511.                 // If request is cancelled, the result arrays are empty.
  512.                 if (grantResults.length > 0
  513.                         && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  514.                     mLocationPermissionGranted = true;
  515.                 }
  516.             }
  517.         }
  518.         updateLocationUI();
  519.     }
  520.  
  521.     private FrameData getBounds() {
  522.         LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
  523.         LatLng boundsNorthEast = bounds.northeast;
  524.         LatLng boundsSouthWest = bounds.southwest;
  525.         return new FrameData(boundsSouthWest.latitude, boundsSouthWest.longitude,
  526.                 boundsNorthEast.latitude, boundsNorthEast.longitude);
  527.     }
  528.  
  529.     private void init() {
  530.         double deltaLatitude = 1.0 / 3600, deltaLongitude = 1.0 / 2400;//Дельта для формироваия квадратиков
  531.         for (int i = 0; i < squaresDataList.size(); i++) {
  532.             Coordinates coordinates = new Coordinates(squaresDataList.get(i).getVertical_id(), squaresDataList.get(i).getHorizontal_id());
  533.             if (!polygonTreeMap.containsKey(coordinates)) {
  534.                 polygonTreeMap.put(coordinates, null);
  535.                 PolygonOptions polygonOptions = new PolygonOptions()
  536.                         .add(new LatLng(coordinates.vertical_id / 3600.0 + deltaLatitude, coordinates.horizontal_id / 2400.0))
  537.                         .add(new LatLng(coordinates.vertical_id / 3600.0, coordinates.horizontal_id / 2400.0))
  538.                         .add(new LatLng(coordinates.vertical_id / 3600.0, coordinates.horizontal_id / 2400.0 + deltaLongitude))
  539.                         .add(new LatLng(coordinates.vertical_id / 3600.0 + deltaLatitude, coordinates.horizontal_id / 2400.0 + deltaLongitude))
  540.                         .strokeColor(Color.argb(100, 0, 0, 0)).strokeWidth(2)
  541.                         .fillColor(Color.parseColor(squaresDataList.get(i).getColor()));
  542.                 polygonTreeMap.put(coordinates, mMap.addPolygon(polygonOptions));
  543.  
  544.             } else if (polygonTreeMap.get(coordinates).getFillColor() != Color.parseColor(squaresDataList.get(i).getColor())){
  545.                 polygonTreeMap.get(coordinates).setFillColor(Color.parseColor(squaresDataList.get(i).getColor()));
  546.             }
  547.         }
  548.     }
  549.  
  550.     /**
  551.      * Updates the map's UI settings based on whether the user has granted location permission.
  552.      */
  553.  
  554.     private void updateLocationUI() {
  555.         if (mMap == null) {
  556.             return;
  557.         }
  558.         try {
  559.             if (mLocationPermissionGranted) {
  560.                 mMap.setMyLocationEnabled(true);
  561.                 mMap.getUiSettings().setMyLocationButtonEnabled(true);
  562.             } else {
  563.                 mMap.setMyLocationEnabled(false);
  564.                 mMap.getUiSettings().setMyLocationButtonEnabled(false);
  565.                 mLastKnownLocation = null;
  566.  
  567.                 getLocationPermission();
  568.             }
  569.         } catch (SecurityException e) {
  570.             Log.e("Exception: %s", e.getMessage());
  571.         }
  572.     }
  573.  
  574.     @Override
  575.     protected void onResume() {
  576.         super.onResume();
  577.         mTimer.schedule(new MyTimerTask(), 200, 5000);
  578.     }
  579.  
  580.     @Override
  581.     protected void onPause() {
  582.         super.onPause();
  583.         mTimer.cancel();
  584.     }
  585. }
Advertisement
Add Comment
Please, Sign In to add comment