Advertisement
Guest User

Untitled

a guest
Jan 14th, 2020
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.20 KB | None | 0 0
  1. public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
  2.  
  3. private GoogleMap mMap;
  4. private FusedLocationProviderClient mFusedLocationProviderClient;
  5. private PlacesClient placesClient;
  6. private List<AutocompletePrediction> predictionList;
  7.  
  8. private Location mLastKnownLocation;
  9. private LocationCallback locationCallback;
  10.  
  11. private MaterialSearchBar materialSearchBar;
  12. private View mapView;
  13. private Button btnFind;
  14. private RippleBackground rippleBg;
  15.  
  16. private final float DEFAULT_ZOOM = 15;
  17.  
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_map);
  22.  
  23. materialSearchBar = findViewById(R.id.searchBar);
  24. btnFind = findViewById(R.id.btn_find);
  25. rippleBg = findViewById(R.id.ripple_bg);
  26.  
  27. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  28. mapFragment.getMapAsync(this);
  29. mapView = mapFragment.getView();
  30.  
  31. mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);
  32. Places.initialize(MapActivity.this, getString(R.string.google_maps_api));
  33. placesClient = Places.createClient(this);
  34. final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
  35.  
  36. materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
  37. @Override
  38. public void onSearchStateChanged(boolean enabled) {
  39.  
  40. }
  41.  
  42. @Override
  43. public void onSearchConfirmed(CharSequence text) {
  44. startSearch(text.toString(), true, null, true);
  45. }
  46.  
  47. @Override
  48. public void onButtonClicked(int buttonCode) {
  49. if (buttonCode == MaterialSearchBar.BUTTON_NAVIGATION) {
  50. //opening or closing a navigation drawer
  51. } else if (buttonCode == MaterialSearchBar.BUTTON_BACK) {
  52. materialSearchBar.disableSearch();
  53. }
  54. }
  55. });
  56.  
  57. materialSearchBar.addTextChangeListener(new TextWatcher() {
  58. @Override
  59. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  60.  
  61. }
  62.  
  63. @Override
  64. public void onTextChanged(CharSequence s, int start, int before, int count) {
  65. FindAutocompletePredictionsRequest predictionsRequest = FindAutocompletePredictionsRequest.builder()
  66. .setTypeFilter(TypeFilter.ADDRESS)
  67. .setSessionToken(token)
  68. .setQuery(s.toString())
  69. .build();
  70. placesClient.findAutocompletePredictions(predictionsRequest).addOnCompleteListener(new OnCompleteListener<FindAutocompletePredictionsResponse>() {
  71. @Override
  72. public void onComplete(@NonNull Task<FindAutocompletePredictionsResponse> task) {
  73. if (task.isSuccessful()) {
  74. FindAutocompletePredictionsResponse predictionsResponse = task.getResult();
  75. if (predictionsResponse != null) {
  76. predictionList = predictionsResponse.getAutocompletePredictions();
  77. List<String> suggestionsList = new ArrayList<>();
  78. for (int i = 0; i < predictionList.size(); i++) {
  79. AutocompletePrediction prediction = predictionList.get(i);
  80. suggestionsList.add(prediction.getFullText(null).toString());
  81. }
  82. materialSearchBar.updateLastSuggestions(suggestionsList);
  83. if (!materialSearchBar.isSuggestionsVisible()) {
  84. materialSearchBar.showSuggestionsList();
  85. }
  86. }
  87. } else {
  88. Log.i("mytag", "prediction fetching task unsuccessful");
  89. }
  90. }
  91. });
  92. }
  93.  
  94. @Override
  95. public void afterTextChanged(Editable s) {
  96.  
  97. }
  98. });
  99.  
  100. materialSearchBar.setSuggstionsClickListener(new SuggestionsAdapter.OnItemViewClickListener() {
  101. @Override
  102. public void OnItemClickListener(int position, View v) {
  103. if (position >= predictionList.size()) {
  104. return;
  105. }
  106. AutocompletePrediction selectedPrediction = predictionList.get(position);
  107. String suggestion = materialSearchBar.getLastSuggestions().get(position).toString();
  108. materialSearchBar.setText(suggestion);
  109.  
  110. new Handler().postDelayed(new Runnable() {
  111. @Override
  112. public void run() {
  113. materialSearchBar.clearSuggestions();
  114. }
  115. }, 1000);
  116. InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  117. if (imm != null)
  118. imm.hideSoftInputFromWindow(materialSearchBar.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
  119. final String placeId = selectedPrediction.getPlaceId();
  120. List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG);
  121.  
  122. FetchPlaceRequest fetchPlaceRequest = FetchPlaceRequest.builder(placeId, placeFields).build();
  123. placesClient.fetchPlace(fetchPlaceRequest).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
  124. @Override
  125. public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
  126. Place place = fetchPlaceResponse.getPlace();
  127. Log.i("mytag", "Place found: " + place.getName());
  128. LatLng latLngOfPlace = place.getLatLng();
  129. if (latLngOfPlace != null) {
  130. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngOfPlace, DEFAULT_ZOOM));
  131. }
  132. }
  133. }).addOnFailureListener(new OnFailureListener() {
  134. @Override
  135. public void onFailure(@NonNull Exception e) {
  136. if (e instanceof ApiException) {
  137. ApiException apiException = (ApiException) e;
  138. apiException.printStackTrace();
  139. int statusCode = apiException.getStatusCode();
  140. Log.i("mytag", "place not found: " + e.getMessage());
  141. Log.i("mytag", "status code: " + statusCode);
  142. }
  143. }
  144. });
  145. }
  146.  
  147. @Override
  148. public void OnItemDeleteListener(int position, View v) {
  149.  
  150. }
  151. });
  152. btnFind.setOnClickListener(new View.OnClickListener() {
  153. @Override
  154. public void onClick(View v) {
  155. LatLng currentMarkerLocation = mMap.getCameraPosition().target;
  156. rippleBg.startRippleAnimation();
  157. new Handler().postDelayed(new Runnable() {
  158. @Override
  159. public void run() {
  160. rippleBg.stopRippleAnimation();
  161. startActivity(new Intent(MapActivity.this, PermissionsActivity.class));
  162. finish();
  163. }
  164. }, 3000);
  165.  
  166. }
  167. });
  168. }
  169.  
  170.  
  171. @SuppressLint("MissingPermission")
  172. @Override
  173. public void onMapReady(GoogleMap googleMap) {
  174. mMap = googleMap;
  175. mMap.setMyLocationEnabled(true);
  176. mMap.getUiSettings().setMyLocationButtonEnabled(true);
  177.  
  178. if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null) {
  179. View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
  180. RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
  181. layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
  182. layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
  183. layoutParams.setMargins(0, 0, 40, 180);
  184. }
  185.  
  186. //check if gps is enabled or not and then request user to enable it
  187. LocationRequest locationRequest = LocationRequest.create();
  188. locationRequest.setInterval(10000);
  189. locationRequest.setFastestInterval(5000);
  190. locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  191.  
  192. LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
  193.  
  194. SettingsClient settingsClient = LocationServices.getSettingsClient(MapActivity.this);
  195. Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
  196.  
  197. task.addOnSuccessListener(MapActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
  198. @Override
  199. public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
  200. getDeviceLocation();
  201. }
  202. });
  203.  
  204. task.addOnFailureListener(MapActivity.this, new OnFailureListener() {
  205. @Override
  206. public void onFailure(@NonNull Exception e) {
  207. if (e instanceof ResolvableApiException) {
  208. ResolvableApiException resolvable = (ResolvableApiException) e;
  209. try {
  210. resolvable.startResolutionForResult(MapActivity.this, 51);
  211. } catch (IntentSender.SendIntentException e1) {
  212. e1.printStackTrace();
  213. }
  214. }
  215. }
  216. });
  217.  
  218. mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
  219. @Override
  220. public boolean onMyLocationButtonClick() {
  221. if (materialSearchBar.isSuggestionsVisible())
  222. materialSearchBar.clearSuggestions();
  223. if (materialSearchBar.isSearchEnabled())
  224. materialSearchBar.disableSearch();
  225. return false;
  226. }
  227. });
  228. }
  229.  
  230. @Override
  231. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  232. super.onActivityResult(requestCode, resultCode, data);
  233. if (requestCode == 51) {
  234. if (resultCode == RESULT_OK) {
  235. getDeviceLocation();
  236. }
  237. }
  238. }
  239.  
  240. @SuppressLint("MissingPermission")
  241. private void getDeviceLocation() {
  242. mFusedLocationProviderClient.getLastLocation()
  243. .addOnCompleteListener(new OnCompleteListener<Location>() {
  244. @Override
  245. public void onComplete(@NonNull Task<Location> task) {
  246. if (task.isSuccessful()) {
  247. mLastKnownLocation = task.getResult();
  248. if (mLastKnownLocation != null) {
  249. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
  250. } else {
  251. final LocationRequest locationRequest = LocationRequest.create();
  252. locationRequest.setInterval(10000);
  253. locationRequest.setFastestInterval(5000);
  254. locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  255. locationCallback = new LocationCallback() {
  256. @Override
  257. public void onLocationResult(LocationResult locationResult) {
  258. super.onLocationResult(locationResult);
  259. if (locationResult == null) {
  260. return;
  261. }
  262. mLastKnownLocation = locationResult.getLastLocation();
  263. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
  264. mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
  265. }
  266. };
  267. mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
  268.  
  269. }
  270. } else {
  271. Toast.makeText(MapActivity.this, "unable to get last location", Toast.LENGTH_SHORT).show();
  272. }
  273. }
  274. });
  275. }
  276. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement