Partage
  • Partager sur Facebook
  • Partager sur Twitter

Problem NearbySearch avec Retrofit API google map

Sujet résolu
    1 mars 2022 à 10:28:54

    Bonjour,

    Je créé une application mobile avec retrofit en utilisant l'API Google Map et j'aimerais afficher uniquement un type d'établissement lorsque la map s'affiche sur mon écran.

    Seulement après plusieurs essais, je n'arrive toujours pas à afficher un seul type d'établissement.

    Voici mon code :

    public interface GoogleMapAPI {
    
        @GET("nearbysearch/json")
        Call<PlaceResults> getNearby(@Query("radius") int radius,
                                     @Query("type") String type,
                                     @Query("key") String key);
    
        @GET("details/json")
        Call<DetailsPlaces> getDetailsPlaces(@Query("place_id") String placeId,
                                             @Query("fields") String fields,
                                             @Query("key") String key);
    
    }
    public class PlaceResults {
    
        @SerializedName("results")
        @Expose
        private final List<Result> results;
    
        public PlaceResults(List<Result> results) {
            this.results = results;
    
        }
    
        public List<Result> getResult() {
            return results;
        }
    }
    public class Result {
    
        @SerializedName("place_id")
        @Expose
        private final String place_id;
    
        @SerializedName("type")
        @Expose
        private final String type;
    
        @SerializedName("geometry")
        @Expose
        private final Geometry geometry;
    
        @SerializedName("name")
        @Expose
        private final String name;
    
        @SerializedName("opening_hours")
        @Expose
        private final OpeningHours opening_hours;
    
        @SerializedName("website")
        @Expose
        private final String website;
    
        @SerializedName("phone_number")
        @Expose
        private final String phone_number;
    
        @SerializedName("address")
        @Expose
        private final String address;
    
        @SerializedName("rating")
        @Expose
        private final Float rating;
    
        @SerializedName("photos")
        @Expose
        private final List<Photo> photos;
    
        public Result(String place_id, String type, Geometry geometry, String name, OpeningHours opening_hours, String website, String phone_number, String address, Float rating, List<Photo> photos) {
            this.place_id = place_id;
            this.type = type;
            this.geometry = geometry;
            this.name = name;
            this.opening_hours = opening_hours;
            this.website = website;
            this.phone_number = phone_number;
            this.address = address;
            this.rating = rating;
            this.photos = photos;
        }
    
        public String getPlace_id() {
            return place_id;
        }
    
        public String getType() {
            return type;
        }
    
        public Geometry getGeometry() {
            return geometry;
        }
    
        public String getName() {
            return name;
        }
    
        public OpeningHours getOpening_hours() {
            return opening_hours;
        }
    
        public String getWebsite() {
            return website;
        }
    
        public String phone_number() {
            return phone_number;
        }
    
        public String getAddress() {
            return address;
        }
    
        public Float getRating() {
            return rating;
        }
    
        public List<Photo> getPhotos() {
            return photos;
        }
    }
    
    public class APIClient {
    
        private static final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://maps.googleapis.com/maps/api/place/")
                .client(new OkHttpClient.Builder().build())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                .build();
    
        public static GoogleMapAPI getGoogleMapAPI() {
            return retrofit.create(GoogleMapAPI.class);
        }
    }
    public class RetrofitRepository {
    
        private final GoogleMapAPI mGoogleMapAPI;
    
        public RetrofitRepository(GoogleMapAPI googleMapAPI) {
            this.mGoogleMapAPI = googleMapAPI;
        }
    
        public MutableLiveData <List<Result>> getPlaceResultsLiveData() {
            MutableLiveData <List<Result>> PlaceResultsMutableLiveData = new MutableLiveData<>();
            mGoogleMapAPI.getNearby(1000, "restaurant", BuildConfig.MAPS_API_KEY).enqueue(new Callback<PlaceResults>() {
                    @Override
                    public void onResponse(@NonNull Call<PlaceResults> call, @NonNull Response<PlaceResults> response) {
                        assert response.body() != null;
                        PlaceResultsMutableLiveData.setValue(response.body().getResult());
                    }
                    @Override
                    public void onFailure(@NonNull Call<PlaceResults> call, @NonNull Throwable t) {
                        PlaceResultsMutableLiveData.setValue(null);
                    }
                });
            return PlaceResultsMutableLiveData;
        }
    }
    public class MapFragment extends Fragment implements OnMapReadyCallback {
    
        private Location mLocation;
        private Location mLocationL;
        private FusedLocationProviderClient mFusedLocationProviderClient;
        private GoogleMap mMap;
        private RestaurantViewModel mRestaurantViewModel;
        private final RetrofitRepository mRetrofitRepository = new RetrofitRepository(APIClient.getGoogleMapAPI());
        int radius = 1000;
        private static final float DEFAULT_ZOOM = 15;
        private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
    
        public static MapFragment newInstance() {
            return (new MapFragment());
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_map, container, false);
            mRestaurantViewModel = new ViewModelProvider(requireActivity(), ViewModelFactory.getInstance()).get(RestaurantViewModel.class);
            return view;
        }
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map);
            assert mapFragment != null;
            mapFragment.getMapAsync(this);
            mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(Objects.requireNonNull(getActivity()));
            FloatingActionButton floatingActionButton = view.findViewById(R.id.fab_location);
            floatingActionButton.setOnClickListener(v -> getCurrentLocation());
        }
    
        private void getCurrentLocation() {
            Dexter.withContext(getActivity())
                    .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                    .withListener(new PermissionListener() {
                        @SuppressLint("MissingPermission")
                        @Override
                        public void onPermissionGranted(PermissionGrantedResponse response) {
                            mFusedLocationProviderClient.getLastLocation().addOnCompleteListener(task -> {
                                if (task.isSuccessful()) {
                                    mLocation = task.getResult();
                                    if (mLocation != null) {
                                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLocation.getLatitude(), mLocation.getLongitude()), DEFAULT_ZOOM));
                                    } else {
                                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
                                        mMap.getUiSettings().setMyLocationButtonEnabled(false);
    
                                    }
                                }
                            });
                        }
    
                        @Override
                        public void onPermissionDenied(PermissionDeniedResponse response) {/* ... */}
    
                        @Override
                        public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
                    }).check();
        }
    
        @SuppressLint("MissingPermission")
        @Override
        public void onMapReady(@NonNull GoogleMap googleMap) {
            mMap = googleMap;
            getCurrentLocation();
            mRetrofitRepository.getPlaceResultsLiveData().observe(requireActivity(), restaurants -> {
                try {
                    mMap.clear();
                    for (Result r : restaurants) {
                        double lat = r.getGeometry().getLocation().getLat();
                        double lng = r.getGeometry().getLocation().getLng();
                        String name = r.getName();
                        MarkerOptions markerOptions = new MarkerOptions();
                        LatLng latLng = new LatLng(lat, lng);
                        markerOptions.position(latLng);
                        markerOptions.title(name);
                        mMap.addMarker(markerOptions);
                    }
                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }
            });
        }
    }



    Merci d'avance pour votre aide



    -
    Edité par Fabrice Bachmann 5 mars 2022 à 23:49:04

    • Partager sur Facebook
    • Partager sur Twitter

    Problem NearbySearch avec Retrofit API google map

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown