Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/220.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在卡视图中为附近的每个餐厅获取不同的地图_Android_Google Places Api_Android Cardview_Android Recyclerview - Fatal编程技术网

Android 如何在卡视图中为附近的每个餐厅获取不同的地图

Android 如何在卡视图中为附近的每个餐厅获取不同的地图,android,google-places-api,android-cardview,android-recyclerview,Android,Google Places Api,Android Cardview,Android Recyclerview,我的代码中缺少什么,因为我无法在Recyclerview中的每个卡视图中显示附近的餐厅。我在单一视图中获取所有位置,我需要在卡视图中为每个附近的餐厅获取不同的地图。我已经使用改装从api获取数据 适配器类 public class ListMapAdapter extends RecyclerView.Adapter<ListMapAdapter.ViewHolder> { private GoogleMap mMap; private Context mCtx; private

我的代码中缺少什么,因为我无法在Recyclerview中的每个卡视图中显示附近的餐厅。我在单一视图中获取所有位置,我需要在卡视图中为每个附近的餐厅获取不同的地图。我已经使用改装从api获取数据

适配器类

public class ListMapAdapter extends RecyclerView.Adapter<ListMapAdapter.ViewHolder> {

private GoogleMap mMap;
private Context mCtx;
private List<Result> mapList;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;

public ListMapAdapter(Context mCtx, List<Result> mapList) {
    this.mCtx = mCtx;
    this.mapList = mapList;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.item_list, null);
    return new ViewHolder(view);
}

@Override
public void onViewRecycled(ViewHolder holder) {
    super.onViewRecycled(holder);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Result mapData = mapList.get(position);
    mapList.set(position, mapData);
}

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


protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(mCtx)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                }

                @Override
                public void onConnectionSuspended(int i) {
                }
            })
            .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                }
            })
            .addApi(LocationServices.API)

            .build();
}


public class ViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {

    MapView map;
    CardView card;


    public ViewHolder(View itemView) {
        super(itemView);
        map = itemView.findViewById(R.id.mapList);
        card = itemView.findViewById(R.id.card);
        if (map != null) {
            map.onCreate(null);
            map.onResume();
            map.getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        GoogleMapOptions options = new GoogleMapOptions().liteMode(true);
        MapsInitializer.initialize(itemView.getContext());
        mMap = googleMap;


        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(mCtx,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        } else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
        build_retrofit_and_get_response("restaurant");
    }

    private void build_retrofit_and_get_response(String type) {
        String url = "https://maps.googleapis.com/maps/";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitMaps service = retrofit.create(RetrofitMaps.class);

        Call<Example> call = service.getNearbyPlaces(type, latitude + "," + longitude, PROXIMITY_RADIUS);

        call.enqueue(new Callback<Example>() {
            @Override
            public void onResponse(Call<Example> call, Response<Example> response) {

                try {
                    mMap.clear();
                    // This loop will go through all the results and add marker on each location.
                    for (int i = 0; i < response.body().getResults().size(); i++) {
                        Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
                        Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
                        String placeName = response.body().getResults().get(i).getName();
                        String vicinity = response.body().getResults().get(i).getVicinity();
                        MarkerOptions markerOptions = new MarkerOptions();
                        LatLng latLng = new LatLng(lat, lng);
                        // Position of Marker on Map
                        markerOptions.position(latLng);
                        // Adding Title to the Marker
                        markerOptions.title(placeName + " : " + vicinity);
                        // Adding Marker to the Camera.
                        Marker m = mMap.addMarker(markerOptions);
                        // Adding colour to the marker
                        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                        // move map camera
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
                    }
                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }
            }

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

}
公共类ListMapAdapter扩展了RecyclerView.Adapter{ 私有谷歌地图; 私有上下文mCtx; 私有列表映射列表; 双纬度; 双经度; 私人int近距离_半径=10000; GoogleapClient MGoogleapClient; 公共ListMapAdapter(上下文mCtx,列表映射列表){ this.mCtx=mCtx; this.mapList=mapList; } @凌驾 public ViewHolder onCreateViewHolder(视图组父级,int-viewType){ LayoutFlater充气机=LayoutFlater.from(mCtx); 视图=充气机。充气(R.layout.item_列表,空); 返回新的ViewHolder(视图); } @凌驾 视图上的公共无效已回收(视图持有人){ super.onViewRecycled(支架); } @凌驾 公共无效onBindViewHolder(ViewHolder,int位置){ 结果mapData=mapList.get(位置); mapList.set(位置、地图数据); } @凌驾 public int getItemCount(){ 返回mapList.size(); } 受保护的同步无效BuildGoogleAppClient(){ mgoogleapclient=新的Googleapclient.Builder(mCtx) .addConnectionCallbacks(新的GoogleAppClient.ConnectionCallbacks(){ @凌驾 未连接的公共无效(@Nullable Bundle){ } @凌驾 公共空间连接暂停(int i){ } }) .addOnConnectionFailedListener(新的GoogleAppClient.OnConnectionFailedListener(){ @凌驾 public void onconnection失败(@NonNull ConnectionResult ConnectionResult){ } }) .addApi(LocationServices.API) .build(); } 公共类ViewHolder扩展了RecyclerView.ViewHolder在MapReadyCallback上实现{ 地图视图; CardView卡; 公共视图持有者(视图项视图){ 超级(项目视图); map=itemView.findviewbyd(R.id.mapList); card=itemView.findviewbyd(R.id.card); if(map!=null){ map.onCreate(null); onResume(); getMapAsync(this); } } @凌驾 4月1日公开作废(谷歌地图谷歌地图){ GoogleMapOptions=new GoogleMapOptions().liteMode(true); 初始化(itemView.getContext()); mMap=谷歌地图; mMap.setMapType(GoogleMap.MAP\u TYPE\u NORMAL); //初始化Google Play服务 if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){ if(ContextCompat.checkSelfPermission)(mCtx, 清单.权限.访问(位置) ==PackageManager.权限(已授予){ buildGoogleAppClient(); mMap.setMyLocationEnabled(真); } }否则{ buildGoogleAppClient(); mMap.setMyLocationEnabled(真); } 建造、改造和获得响应(“餐厅”); } 私有void生成\u改装\u和\u获取\u响应(字符串类型){ 字符串url=”https://maps.googleapis.com/maps/"; 改装改装=新改装.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .build(); RefundationMaps服务=Refundation.create(RefundationMaps.class); Call Call=service.getNearbyPlaces(类型,纬度+“,”+经度,邻近半径); call.enqueue(新回调(){ @凌驾 公共void onResponse(调用、响应){ 试一试{ mMap.clear(); //该循环将遍历所有结果,并在每个位置添加标记。 对于(int i=0;i }

主列表活动

public class ListActivity extends AppCompatActivity {
@BindView(R.id.rvListMap)
RecyclerView recyclerView;
List<Result> productList;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);
    ButterKnife.bind(this);
    recyclerView = findViewById(R.id.rvListMap);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    productList = new ArrayList<>();
    ListMapAdapter adapter = new ListMapAdapter(this, productList);
    recyclerView.setAdapter(adapter);


}
公共类ListActivity扩展了AppCompatActivity{
@BindView(R.id.rvListMap)
回收视图回收视图;
列出产品清单;
@凌驾
创建时受保护的void(@Nullable Bundle savedInstanceState){
苏佩
public interface RetrofitMaps {
    /*
   * Retrofit get annotation with our URL
   * And our method that will return us details of student.
   */
    @GET("api/place/nearbysearch/json?sensor=true&key=AIzaSyDN7RJFmImYAca96elyZlE5s_fhX-MMuhk")
    Call<Example> getNearbyPlaces(@Query("type") String type, @Query("location") String location, @Query("radius") int radius);
}
@SerializedName("geometry")
@Expose
private Geometry geometry;
@SerializedName("icon")
@Expose
private String icon;
@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("opening_hours")
@Expose
private OpeningHours openingHours;
@SerializedName("photos")
@Expose
private List<Photo> photos = new ArrayList<Photo>();
@SerializedName("place_id")
@Expose
private String placeId;
@SerializedName("rating")
@Expose
private Double rating;
@SerializedName("reference")
@Expose
private String reference;
@SerializedName("scope")
@Expose
private String scope;
@SerializedName("types")
@Expose
private List<String> types = new ArrayList<String>();
@SerializedName("vicinity")
@Expose
private String vicinity;
@SerializedName("price_level")
@Expose
private Integer priceLevel;

/**
 * @return The geometry
 */
public Geometry getGeometry() {
    return geometry;
}

/**
 * @param geometry The geometry
 */
public void setGeometry(Geometry geometry) {
    this.geometry = geometry;
}

/**
 * @return The icon
 */
public String getIcon() {
    return icon;
}

/**
 * @param icon The icon
 */
public void setIcon(String icon) {
    this.icon = icon;
}

/**
 * @return The id
 */
public String getId() {
    return id;
}

/**
 * @param id The id
 */
public void setId(String id) {
    this.id = id;
}

/**
 * @return The name
 */
public String getName() {
    return name;
}

/**
 * @param name The name
 */
public void setName(String name) {
    this.name = name;
}

/**
 * @return The openingHours
 */
public OpeningHours getOpeningHours() {
    return openingHours;
}

/**
 * @param openingHours The opening_hours
 */
public void setOpeningHours(OpeningHours openingHours) {
    this.openingHours = openingHours;
}

/**
 * @return The photos
 */
public List<Photo> getPhotos() {
    return photos;
}

/**
 * @param photos The photos
 */
public void setPhotos(List<Photo> photos) {
    this.photos = photos;
}

/**
 * @return The placeId
 */
public String getPlaceId() {
    return placeId;
}

/**
 * @param placeId The place_id
 */
public void setPlaceId(String placeId) {
    this.placeId = placeId;
}

/**
 * @return The rating
 */
public Double getRating() {
    return rating;
}

/**
 * @param rating The rating
 */
public void setRating(Double rating) {
    this.rating = rating;
}

/**
 * @return The reference
 */
public String getReference() {
    return reference;
}

/**
 * @param reference The reference
 */
public void setReference(String reference) {
    this.reference = reference;
}

/**
 * @return The scope
 */
public String getScope() {
    return scope;
}

/**
 * @param scope The scope
 */
public void setScope(String scope) {
    this.scope = scope;
}

/**
 * @return The types
 */
public List<String> getTypes() {
    return types;
}

/**
 * @param types The types
 */
public void setTypes(List<String> types) {
    this.types = types;
}

/**
 * @return The vicinity
 */
public String getVicinity() {
    return vicinity;
}

/**
 * @param vicinity The vicinity
 */
public void setVicinity(String vicinity) {
    this.vicinity = vicinity;
}

/**
 * @return The priceLevel
 */
public Integer getPriceLevel() {
    return priceLevel;
}

/**
 * @param priceLevel The price_level
 */
public void setPriceLevel(Integer priceLevel) {
    this.priceLevel = priceLevel;
}
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=22.4892,72.7996&radius=500&types=food&key=<your places api key>
{
"html_attributions": [],
"results": [
    {
        "geometry": {
            "location": {
            "lat": 22.4909137,
            "lng": 72.799812
            },
            "viewport": {}      
        },
        "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
        "id": "f5472c3bf89ee78bf6afaf46510eaff1b2276481",
        "name": "Dolly Studio",
        "place_id": "ChIJ4-N6Z35UXjkRele_KJ8p24w",
        "reference": "CmRSAAAAGDR9Rp83US-bOIYdqRVTf..........",
        "scope": "GOOGLE",
        "types": [
            "grocery_or_supermarket",
            "store",
            "food",
            "point_of_interest",
            "establishment"
        ],
    "vicinity": "Petlad - Sunav Road, Aaradhna Society, Rangaipura, Petlad"
    }
],
"status": "OK"
}
private void build_retrofit_and_get_response(String type) {
    String url = "https://maps.googleapis.com/maps/";

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitMaps service = retrofit.create(RetrofitMaps.class);

    Call<Example> call = service.getNearbyPlaces(type, latitude + "," + longitude, PROXIMITY_RADIUS);

    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {

            try {
                mMap.clear();
                // This loop will go through all the results and add marker on each location.
                for (int i = 0; i < response.body().getResults().size(); i++) {

                    Result result= new Result(); //create a result object for a single cardview item

                    //add everthing you need in one cardview to this result object

                    productList.add(result); // add this single card item to your productlist
                    adapter.notifyDataSetChanged(); //notify adapter that item is added

                }
            } catch (Exception e) {
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            }
        }

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