Я сделал все необходимые разрешения для menifest и runtime, но он не работает на моих устройствах для текущего местоположения на карте Google
public class MapFragment extends Fragment implements OnMapReadyCallback, AdapterView.OnItemClickListener {
View view;
ImageView locAddress;
AppLocationService appLocationService;
AutoCompleteTextView edtStartPoint;
EditText togo;
private static final String LOG_TAG = "Google Places Autocomplete";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "MY_API_KEY";
private static final int REQUEST_FINE_LOCATION = 11;
private GoogleMap mMap;
ImageView imgLoc;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_main, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView);
if (mapFragment != null) {
mapFragment.getMapAsync(this);
}
locAddress = view.findViewById(R.id.locAddress);
edtStartPoint = view.findViewById(R.id.edtStartPoint);
imgLoc = view.findViewById(R.id.imgLoc);
edtStartPoint.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item_text));
edtStartPoint.setOnItemClickListener(this);
appLocationService = new AppLocationService(
getActivity());
if (InternetConnection.checkConnection(getActivity())) {
} else {
showSnack(true);
}
return view;
}
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
LatLng sydney = new LatLng(-34, 151);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (checkPermissions()) {
setMyLocationEnabled();
}
mMap.getUiSettings().setMyLocationButtonEnabled(true);
map.setOnMapClickListener(latLng -> {
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
bottomSheetFragment.show(getActivity().getSupportFragmentManager(), bottomSheetFragment.getTag());
});
}
public static ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&components=country:gr");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
Log.e("@@sb", sb.toString());
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e("@@", "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e("@@", "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
resultList = new ArrayList(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("====");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e("@@", "Cannot process JSON results", e);
}
return resultList;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String str = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public int getCount() {
return resultList.size();
}
@Override
public String getItem(int index) {
return String.valueOf(resultList.get(index));
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
private void showSnack(boolean isConnected) {
final CoordinatorLayout coordinatorLayout = view.findViewById(R.id.coordinatorLayout);
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "No Internet", Snackbar.LENGTH_LONG)
.setAction("OK", view -> {
Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "ok", Snackbar.LENGTH_SHORT);
snackbar1.show();
});
snackbar.show();
}
private boolean checkPermissions() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
requestPermissions();
return false;
}
}
private void requestPermissions() {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_FINE_LOCATION);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_FINE_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setMyLocationEnabled();
} else {
}
}
}
}
private void setMyLocationEnabled() {
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
//TODO:
}
});
}
}
Пожалуйста, предложите мне заранее спасибо, я был бы признателен за каждый ответ