在回收站视图中使用 google 地图 api

Consume google map api inside recycler view

我正在开发一个 nearyPlaces 应用程序,该应用程序可以帮助用户获取他们周围的附近位置。我使用 retrofit 库从 google api 获取响应。如您所见 here,一切都完美无缺。所以。我想在 recyclerView 内解析此结果,就像 google 地图一样。问题是在 consuming 之后 api,它显示为 object 而不是 arrayList

我真的需要这方面的指导,因为这让我头痛了几周。

请求接口

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

interface RequestInterface {
    @GET("api/place/nearbysearch/json?sensor=true&key="+Constants.API_KEY)
    Call <NearbyPlaces.Result> getPlacesJson(@Query("type") String type, @Query("location") String location, @Query("radius") int radius);
}

MapActivity.java

 private void getPlacesResponse(String type) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://maps.googleapis.com/maps/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface requestInteface = retrofit.create(RequestInterface.class);
        Call<NearbyPlaces.Result> call = requestInteface.getPlacesJson(type, latitude + "," + longitude, proximityRadius);

        call.enqueue(new Callback<NearbyPlaces.Result>() {
            @Override
            public void onResponse(@NonNull  Call<NearbyPlaces.Result> call, @NonNull Response<NearbyPlaces.Result> response) {
              Log.d("error", response.toString());
             placeResultAdapter=new PlaceResultAdapter(MapActivity.this, placeResultAdapter);
//here I need to set an arrayList to my adapter but I can't because the retrofit's data comes as an object instead of arrayList.
                  //    mRecyclerView.setAdapter(placeResultAdapter);
                }

            @Override
            public void onFailure(Call<NearbyPlaces.Result> call, Throwable t) {
                Log.d("error", call.toString() + "  " + t.toString());
            }
        });
    }

附近的地点Class

public class GetNearbyPlaces extends AsyncTask<Object, String,String> {
    private String googlePlaceData;
    private GoogleMap mMap;
   private Context mContext;
   private Bitmap bitmap;
    public GetNearbyPlaces (Context context){
        mContext = context;
    }

    @Override
    protected String doInBackground(Object... objects) {
    mMap = (GoogleMap) objects[0];
        String url = (String) objects[1];
DownloadUrl downloadUrl = new DownloadUrl();
        try {
            googlePlaceData = downloadUrl.ReadTheURL(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return googlePlaceData;
    }

    @Override
    protected void onPostExecute(String s) {
        List<HashMap<String, String>> nearbyPlacesList;
        DataParser dataParser = new DataParser();
        nearbyPlacesList = dataParser.parse(s);
        DisplayNearbyPlaces(nearbyPlacesList);
        Log.d("nearby", nearbyPlacesList.toString());
    }
    private void DisplayNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList){
        for (int i = 0; i<nearbyPlacesList.size(); i++){
            MarkerOptions markerOptions = new MarkerOptions();
            HashMap<String, String> googleNearbyPlace = nearbyPlacesList.get(i);
            String nameOfPlace = googleNearbyPlace.get("place_name");
            String iconLink = googleNearbyPlace.get("icon");
            String vicinity = googleNearbyPlace.get("vicinity");
            double lat = Double.parseDouble(googleNearbyPlace.get("lat"));
            double lng = Double.parseDouble(googleNearbyPlace.get("lng"));
            LatLng latLng = new LatLng(lat, lng);
            markerOptions.position(latLng);
            markerOptions.title(nameOfPlace);
            //load image icon from url;
            Glide.with(mContext)
                    .asBitmap()
                    .apply(RequestOptions.centerCropTransform())
                    .load(iconLink)
                    .listener(new RequestListener<Bitmap>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap bitmap, Transition<? super Bitmap> transition) {
                            Bitmap locator = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.locator_red);
                            Bitmap scaledLocator =Bitmap.createScaledBitmap(locator, 100, 100, true);
                            Bitmap iconBitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
                            Bitmap mergedImages = createSingleImageFromMultipleImages(scaledLocator, tintImage(iconBitmap, Color.WHITE));
                            markerOptions.icon(BitmapDescriptorFactory.fromBitmap(mergedImages));
                            mMap.addMarker(markerOptions);
                            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                            mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
                        }
                    });
        }

    }
    private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){
        Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(firstImage, 0f, 0f, null);
        canvas.drawBitmap(secondImage, 35, 10, null);
        return result;
    }
    public static Bitmap tintImage(Bitmap bitmap, int color) {
        Paint paint = new Paint();
        paint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
        Bitmap bitmapResult = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapResult);
        canvas.drawBitmap(bitmap, 0, 0, paint);
        return bitmapResult;
    }
}

附近地点适配器(已更新)

public class PlaceResultAdapter 扩展 RecyclerView.Adapter { 私人 ArrayList 地方模型; 私有上下文上下文;

public PlaceResultAdapter(Context context, ArrayList<NearbyPlaces.Result> placeModels) {
    this.placeModels=placeModels;
    this.context=context;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.place_result_item,viewGroup,false);
    return new PlaceResultAdapter.ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull PlaceResultAdapter.ViewHolder viewHolder, int i) {
    viewHolder.place_name.setText(placeModels.get(i).getName());
    //Picasso.get().load(placeModels.get(i).getUrl()).into(viewHolder.car_image);
}

@Override
public int getItemCount() {
    return placeModels.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private ImageView place_image;
    private TextView place_name,place_category;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        place_image= itemView.findViewById(R.id.image_view);
        place_name= itemView.findViewById(R.id.title);
        place_category= itemView.findViewById(R.id.category_text);
    }
}

}

型号Class(更新)

public abstract class NearbyPlaces {

public class Result {
    @Expose
    @SerializedName("photos")
    private List<Photos> photos;
    @SerializedName("geometry")
    private Geometry getGeometry;

    @SerializedName("icon")
    private String icon;

    @SerializedName("id")
    private String id;

    @SerializedName("name")
    private String name;

    @SerializedName("vicinity")
    private String vicinity;

    public Geometry getGetGeometry() {
        return getGeometry;
    }
    public List<Photos> getPhotos() {
        return photos;
    }

    public void setPhotos(List<Photos> photos) {
        this.photos = photos;
    }
    public String getIcon() {
        return icon;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getVicinity() {
        return vicinity;
    }

}

public static class Photos {
    @Expose
    @SerializedName("width")
    private int width;
    @Expose
    @SerializedName("photo_reference")
    private String photoReference;
    @Expose
    @SerializedName("html_attributions")
    private List<String> htmlAttributions;
    @Expose
    @SerializedName("height")
    private int height;

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public String getPhotoReference() {
        return photoReference;
    }

    public void setPhotoReference(String photoReference) {
        this.photoReference = photoReference;
    }

    public List<String> getHtmlAttributions() {
        return htmlAttributions;
    }

    public void setHtmlAttributions(List<String> htmlAttributions) {
        this.htmlAttributions = htmlAttributions;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}

public static class Reviews {
    @Expose
    @SerializedName("time")
    private int time;
    @Expose
    @SerializedName("text")
    private String text;
    @Expose
    @SerializedName("relative_time_description")
    private String relativeTimeDescription;
    @Expose
    @SerializedName("rating")
    private int rating;
    @Expose
    @SerializedName("profile_photo_url")
    private String profilePhotoUrl;
    @Expose
    @SerializedName("language")
    private String language;
    @Expose
    @SerializedName("author_url")
    private String authorUrl;
    @Expose
    @SerializedName("author_name")
    private String authorName;

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getRelativeTimeDescription() {
        return relativeTimeDescription;
    }

    public void setRelativeTimeDescription(String relativeTimeDescription) {
        this.relativeTimeDescription = relativeTimeDescription;
    }

    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public String getProfilePhotoUrl() {
        return profilePhotoUrl;
    }

    public void setProfilePhotoUrl(String profilePhotoUrl) {
        this.profilePhotoUrl = profilePhotoUrl;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getAuthorUrl() {
        return authorUrl;
    }

    public void setAuthorUrl(String authorUrl) {
        this.authorUrl = authorUrl;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }
}

public static class Geometry {
    @Expose
    @SerializedName("viewport")
    private Viewport viewport;
    @Expose
    @SerializedName("location")
    private Location location;

    public Viewport getViewport() {
        return viewport;
    }

    public void setViewport(Viewport viewport) {
        this.viewport = viewport;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }
}

public static class Viewport {
    @Expose
    @SerializedName("southwest")
    private Southwest southwest;
    @Expose
    @SerializedName("northeast")
    private Northeast northeast;

    public Southwest getSouthwest() {
        return southwest;
    }

    public void setSouthwest(Southwest southwest) {
        this.southwest = southwest;
    }

    public Northeast getNortheast() {
        return northeast;
    }

    public void setNortheast(Northeast northeast) {
        this.northeast = northeast;
    }
}

public static class Southwest {
    @Expose
    @SerializedName("lng")
    private double lng;
    @Expose
    @SerializedName("lat")
    private double lat;

    public double getLng() {
        return lng;
    }

    public void setLng(double lng) {
        this.lng = lng;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }
}

public static class Northeast {
    @Expose
    @SerializedName("lng")
    private double lng;
    @Expose
    @SerializedName("lat")
    private double lat;

    public double getLng() {
        return lng;
    }

    public void setLng(double lng) {
        this.lng = lng;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }
}

public static class Location {
    @Expose
    @SerializedName("lng")
    private double lng;
    @Expose
    @SerializedName("lat")
    private double lat;

    public double getLng() {
        return lng;
    }

    public void setLng(double lng) {
        this.lng = lng;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }
}

public static class AddressComponents {
    @Expose
    @SerializedName("types")
    private List<String> types;
    @Expose
    @SerializedName("short_name")
    private String shortName;
    @Expose
    @SerializedName("long_name")
    private String longName;

    public List<String> getTypes() {
        return types;
    }

    public void setTypes(List<String> types) {
        this.types = types;
    }

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    public String getLongName() {
        return longName;
    }

    public void setLongName(String longName) {
        this.longName = longName;
    }
}

} 如您所见,我已经在 NearbyPlaces Class 中检索数据,其中包含 AsyncTask class。所以我认为我需要做的是找出如何将数据从我的异步任务传输到我的 adapter,以便我可以用 recyclerView 显示。

根据您的 json 回复创建模型

主要对象

public class Response {

    @SerializedName("results")
    private ArrayList<Result> list;

    public ArrayList<Result> getList() {
        return list;
    }
}

主对象中的数组

public class Result {

    @SerializedName("geometry")
    private Geometry getGeometry;

    @SerializedName("icon")
    private String icon;

    @SerializedName("id")
    private String id;

    @SerializedName("name")
    private String name;

    @SerializedName("vicinity")
    private String vicinity;

    public Geometry getGetGeometry() {
        return getGeometry;
    }

    public String getIcon() {
        return icon;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getVicinity() {
        return vicinity;
    }
}

几何对象

public class Geometry {

   @SerializedName("location")
    private Location location;

    @SerializedName("viewport")
    private ViewPort viewPort;

    public Location getLocation() {
        return location;
    }

    public ViewPort getViewPort() {
        return viewPort;
    }
}

位置对象

public class Location {

    @SerializedName("lat")
    private String lat;

    @SerializedName("lng")
    private String lng;

    public String getLat() {
        return lat;
    }

    public String getLng() {
        return lng;
    }
}

ViewPort 模型

public class ViewPort {

    @SerializedName("northeast")
    private NorthEast northEast;

    @SerializedName("southwest")
    private SouthWest southWest;

    public NorthEast getNorthEast() {
        return northEast;
    }

    public SouthWest getSouthWest() {
        return southWest;
    }
}

东北模式

public class NorthEast {

    @SerializedName("lat")
    private String lat;

    @SerializedName("lng")
    private String lng;

    public String getLat() {
        return lat;
    }

    public String getLng() {
        return lng;
    }
}

西南模式

public class SouthWest {

    @SerializedName("lat")
    private String lat;

    @SerializedName("lng")
    private String lng;

    public String getLat() {
        return lat;
    }

    public String getLng() {
        return lng;
    }
}

1 为所有这些模型创建 class 并复制它们 2 修改你的界面

interface RequestInterface {
    @GET("api/place/nearbysearch/json?sensor=true&key="+Constants.API_KEY)
    Call <Response> getPlacesJson(@Query("type") String type, @Query("location") String location, @Query("radius") int radius);
}

3 修改你的api调用函数

 private void getPlacesResponse(String type) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://maps.googleapis.com/maps/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface requestInteface = retrofit.create(RequestInterface.class);
        Call<Response> call = requestInteface.getPlacesJson(type, latitude + "," + longitude, proximityRadius);

        call.enqueue(new Callback<Response>() {
            @Override
            public void onResponse(@NonNull  Call<Response> call, @NonNull Response<Resonse> response) {
              ArrayList<Result> dataList = response.body().getList();
             placeResultAdapter=new PlaceResultAdapter(MapActivity.this, dataList);
                      mRecyclerView.setAdapter(placeResultAdapter);
                }

            @Override
            public void onFailure(Response> call, Throwable t) {
                Log.d("error", call.toString() + "  " + t.toString());
            }
        });
    }

4 : 现在您可以获取 api 数据。

适配器class

public class PlaceResultAdapter extends RecyclerView.Adapter<PlaceResultAdapter.ViewHolder> {
    private ArrayList<NearbyPlaces.Result> placeModels;
    private Context context;


    public PlaceResultAdapter(Context context, ArrayList<NearbyPlaces.Result> placeModels) {
        this.placeModels=placeModels;
        this.context=context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.place_result_item,viewGroup,false);
        return new PlaceResultAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PlaceResultAdapter.ViewHolder viewHolder, int i) {
        viewHolder.place_name.setText(placeModels.get(i).getName());
        viewHolder.place_category.setText(placeModels.get(i).getTypes().get(0));
String image_url = placeModels.get(i).getIcon();
        //Picasso.get().load(image_url).into(viewHolder.car_image);
    }

    @Override
    public int getItemCount() {
        return placeModels.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView place_image;
        private TextView place_name,place_category;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            place_image= itemView.findViewById(R.id.image_view);
            place_name= itemView.findViewById(R.id.title);
            place_category= itemView.findViewById(R.id.category_text);
        }
    }
}