简体   繁体   English

在回收站视图中使用谷歌地图 API

[英]Consume google map api inside recycler view

I am working on a nearyPlaces application that helps users get nearby locations around them.我正在开发一个nearyPlaces应用程序,该应用程序可帮助用户获取他们周围的附近位置。 I used retrofit library to fetch response from google api.我使用retrofit库从 google api 获取响应。 Everything works perfectly as you can see here .正如您在此处看到的那样,一切都完美无缺。 So.所以。 I want to parse this results inside a recyclerView just like google maps.我想像谷歌地图一样在recyclerView解析这个结果。 The problem is that after consuming the api, it displays as an object instead of an arrayList .问题是在consuming api 后,它显示为一个object而不是arrayList

I really need directions on this as it has given me headache for a few weeks.我真的需要这方面的指导,因为它让我头痛了几个星期。

RequestInterface请求接口

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());
            }
        });
    }

Nearby Places 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;
    }
}

Nearby Places Adapter (Updated)附近地点适配器(更新)

public class PlaceResultAdapter extends RecyclerView.Adapter { private ArrayList placeModels;公共类 PlaceResultAdapter 扩展 RecyclerView.Adapter { private ArrayList 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());
    //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);
    }
}

} }

Model Class (Updated)模型类(更新)

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;
    }
}

} As you can see, am already retrieving the data inside NearbyPlaces Class which contains the AsyncTask class.如您所见,我已经在NearbyPlaces类中检索数据,其中包含AsyncTask类。 So i think what I need to do is find out how to transfer the data from my async task to my adapter so I can show with recyclerView .所以我认为我需要做的是找出如何将数据从我的异步任务传输到我的adapter以便我可以用recyclerView显示。

create models as per your json response根据您的 json 响应创建模型

Main object主要对象

public class Response {

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

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

Array inside main object主对象内的数组

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;
    }
}

Geometry object几何对象

public class Geometry {

   @SerializedName("location")
    private Location location;

    @SerializedName("viewport")
    private ViewPort viewPort;

    public Location getLocation() {
        return location;
    }

    public ViewPort getViewPort() {
        return viewPort;
    }
}

Location object位置对象

public class Location {

    @SerializedName("lat")
    private String lat;

    @SerializedName("lng")
    private String lng;

    public String getLat() {
        return lat;
    }

    public String getLng() {
        return lng;
    }
}

ViewPort model视口模型

public class ViewPort {

    @SerializedName("northeast")
    private NorthEast northEast;

    @SerializedName("southwest")
    private SouthWest southWest;

    public NorthEast getNorthEast() {
        return northEast;
    }

    public SouthWest getSouthWest() {
        return southWest;
    }
}

NorthEast model东北模式

public class NorthEast {

    @SerializedName("lat")
    private String lat;

    @SerializedName("lng")
    private String lng;

    public String getLat() {
        return lat;
    }

    public String getLng() {
        return lng;
    }
}

SouthWest model西南模式

public class SouthWest {

    @SerializedName("lat")
    private String lat;

    @SerializedName("lng")
    private String lng;

    public String getLat() {
        return lat;
    }

    public String getLng() {
        return lng;
    }
}

1 Create class for all these models and copy them 2 Modify your interface 1 为所有这些模型创建类并复制它们 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 Modify your apicall function 3 修改你的apicall函数

 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 : Now you can fetch api data. 4:现在你可以获取api数据了。

Adapter 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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM