用googlemaps在recyclerview中绘制路线

jfewjypa  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(206)

我´我试图在severel谷歌Map上用Recycerview画一条路线,但我不知道为什么´在第一张Map上画不出来,但在另一张Map上画得正确。
我´我用图书馆截击来获取数据。
Recycerview公司:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.directions.route.AbstractRouting;
import com.directions.route.Route;
import com.directions.route.RouteException;
import com.directions.route.Routing;
import com.directions.route.RoutingListener;
import com.example.crossonme.Dependencias.Alertas.Alerta;
import com.example.crossonme.Dependencias.DB.EventosItem;
import com.example.crossonme.Login_Register;
import com.example.crossonme.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements OnMapReadyCallback, RoutingListener{

    Context context;
    public static ArrayList<EventosItem> eventosItemArrayList = new ArrayList<>();
    private OnClick mOnClick;
    GoogleMap mMap;
    MapView mMapView;
    int id, Position;
    private List<Polyline> polylines = null;

    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView tvNome, tvDescricao, dtData;
        OnClick onClick;

        MyViewHolder(View view, OnClick onClick) {
            super(view);
            tvNome = view.findViewById(R.id.evitem_nome);
            tvDescricao = view.findViewById(R.id.evitem_descricao);
            dtData = view.findViewById(R.id.evitem_data);
            mMapView = view.findViewById(R.id.evitem_map);
            this.onClick = onClick;

            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            onClick.onItemClick(getAdapterPosition());
        }
    }
    public MyAdapter(ArrayList<EventosItem> eventosItemArrayList, OnClick onClick) {
        this.eventosItemArrayList = eventosItemArrayList;
        this.mOnClick = onClick;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.evento_item, null, true);
        context = parent.getContext();

        return new MyViewHolder(view, mOnClick);
    }
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        Position = position;

        mMapView.onCreate(null );
        mMapView.onResume();

        Findroutes(eventosItemArrayList.get(Position).getComecoEv(), eventosItemArrayList.get(Position).getFimEv());
        Log.e("TAG", ""+ Position );

        mMapView.getMapAsync(this);

        id = eventosItemArrayList.get(position).getIdEv();
        holder.tvNome.setText(eventosItemArrayList.get(position).getNomeEv());
        holder.tvDescricao.setText(eventosItemArrayList.get(position).getDescricaoEv());
        holder.dtData.setText(eventosItemArrayList.get(position).getDataEv());
    }

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

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap= googleMap;

        googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(context, R.raw.map_theme));

        LatLng Portugal = new LatLng(39.399872, -8.224454);
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Portugal, 6));
    }

    public interface OnClick{
        void onItemClick(int position);
    }

    public void Findroutes(LatLng Start, LatLng End)
    {
        Routing routing = new Routing.Builder()
                .travelMode(AbstractRouting.TravelMode.DRIVING)
                .withListener(this)
                .alternativeRoutes(true)
                .waypoints(Start, End)
                .key("AIzaSyDzsi_tYj6jhR2CiPx9g-d7EEc8BRb6N7g")
                .build();
        routing.execute();
    }

    //Routing call back functions.
    @Override
    public void onRoutingFailure(RouteException e) {

    }

    @Override
    public void onRoutingStart() {
    }

    @Override
    public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
        PolylineOptions polyOptions = new PolylineOptions();
        LatLng polylineStartLatLng=null;
        LatLng polylineEndLatLng=null;

        polylines = new ArrayList<>();
        for (int i = 0; i <route.size(); i++) {

            if(i==shortestRouteIndex)
            {
                polyOptions.color(Color.parseColor("#FF8E06"));
                polyOptions.width(10);
                polyOptions.addAll(route.get(shortestRouteIndex).getPoints());
                Polyline polyline = mMap.addPolyline(polyOptions);
                polylineStartLatLng=polyline.getPoints().get(0);
                int k=polyline.getPoints().size();
                polylineEndLatLng=polyline.getPoints().get(k-1);
                polylines.add(polyline);
            }
        }

        MarkerOptions endMarker = new MarkerOptions();
        endMarker.position(polylineEndLatLng);
        endMarker.title("Destino");
        endMarker.icon(bitmapDescriptorFromVector(context, R.drawable.dt_fim));
        mMap.addMarker(endMarker);

        MarkerOptions beginMarker = new MarkerOptions();
        beginMarker.position(polylineStartLatLng);
        beginMarker.title("Inicio");
        beginMarker.icon(bitmapDescriptorFromVector(context, R.drawable.dt_inicio));
        mMap.addMarker(beginMarker);
    }

    @Override
    public void onRoutingCancelled() {

    }

    private BitmapDescriptor bitmapDescriptorFromVector(Context context, @DrawableRes int vectorDrawableResourceId) {
        Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
        vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
        Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.draw(canvas);
        return BitmapDescriptorFactory.fromBitmap(bitmap);
    }
}

主要活动

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.crossonme.Dependencias.Alertas.Alerta;
import com.example.crossonme.Dependencias.DB.EventosItem;
import com.example.crossonme.Dependencias.DB.SharedPrefManager;
import com.example.crossonme.Dependencias.DB.URLs;
import com.example.crossonme.Dependencias.DB.User;
import com.example.crossonme.Dependencias.DB.VolleySingleton;
import com.example.crossonme.Dependencias.MyAdapter;
import com.example.crossonme.R;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Eventos extends android.app.Activity implements View.OnClickListener, MyAdapter.OnClick
{
    public static ArrayList<EventosItem> eventosItemArrayList = new ArrayList<>();
    EventosItem eventosItem;
    LatLng Inicio, Fim;
    MyAdapter adapter;

    @Override
    public void onCreate(android.os.Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.eventos);

        eventosItemArrayList.clear();

        adapter = new MyAdapter(eventosItemArrayList, this);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.ev_ScrollAtual);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setNestedScrollingEnabled(true);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTOS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //converting response to json object
                            JSONArray array = new JSONArray(response);

                            for (int i = 0; i < array.length(); i++){
                                JSONObject object = array.getJSONObject(i);

                                String[] latlongIni =  object.getString("comeco").split(",");
                                String[] latlongFim =  object.getString("fim").split(",");

                                Inicio = new LatLng(Double.parseDouble(latlongIni[0]), Double.parseDouble(latlongIni[1]));
                                Fim = new LatLng(Double.parseDouble(latlongFim[0]), Double.parseDouble(latlongFim[1]));

                                eventosItem = new EventosItem(object.getString("nome"), object.getString("tipo"),object.getString("descricao"),object.getString("nome_empresa"),object.getInt("id"),object.getString("data"),Inicio,Fim);
                                eventosItemArrayList.add(eventosItem);

                                adapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        new Alerta.MensagemAlerta(Eventos.this, "Erro", error.getMessage());
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                return params;
            }
        };

        VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onItemClick(int position) {
        new Alerta.MensagemAlerta(Eventos.this, "Erro", String.valueOf(position));
    }
}

这是一个项目,我尝试了几件事,但没有帮助。我希望有人能帮助我。
大卫

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题