如何使用群集标记在谷歌地图标记A-Z中添加字母

时间:2014-12-08 12:42:58

标签: android google-maps google-maps-markers cluster-computing google-maps-android-api-2

我有一张包含10个航点的地图,我试图添加字母来指定路径,是" A"起点和" J"结束点。如何使用群集标记实现这一点,如下图所示?到目前为止,这是我的代码:

maps

public class MapaViagem extends FragmentActivity implements ClusterManager.OnClusterClickListener<MyItem>, ClusterManager.OnClusterItemClickListener<MyItem> {

    private GoogleMap googleMap;
    private String rm_IdViagem;
    private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
    private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
    private ArrayList<LatLng> coordList = new ArrayList<LatLng>();
    private ArrayList<String> nomes = new ArrayList<String>();
    private ViagemModel mViagemModel = new ViagemModel();
    private ClusterManager<MyItem> mClusterManager;
    private ProgressDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.maps);

        // Loading map
        initilizeMap();

        // Changing map type
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        // googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

        // Showing / hiding your current location
        googleMap.setMyLocationEnabled(true);

        // Enable / Disable zooming controls
        googleMap.getUiSettings().setZoomControlsEnabled(true);

        // Enable / Disable my location button
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Enable / Disable Compass icon
        googleMap.getUiSettings().setCompassEnabled(true);

        // Enable / Disable Rotate gesture
        googleMap.getUiSettings().setRotateGesturesEnabled(true);

        // Enable / Disable zooming functionality
        googleMap.getUiSettings().setZoomGesturesEnabled(true);

        try {

            Bundle parametros = getIntent().getExtras();
            rm_IdViagem = parametros.getString("id_viagem");

            Repositorio ca = new Repositorio(this);
            mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));

            Repositorio cl = new Repositorio(this);
            mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));


            String waypoints = "waypoints=optimize:true";
            String coordenadas = "";

            //if (mClienteModel != null) {


            //for (int i = 0; i < mClienteModel.size(); i++) {


            Repositorio mRepositorio = new Repositorio(this);
            //mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));


            mEnderecoModel = mRepositorio.getListaEnderecosDaViagem(Integer.valueOf(rm_IdViagem));

            for (int j = 0; j < mEnderecoModel.size(); j++) {


                float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
                float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());

                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 5));

                coordenadas += "|" + latitude + "," + longitude;


                nomes.add(String.valueOf(j));

                coordList.add(new LatLng(latitude, longitude));


                startDemo();


                addItems(coordList, nomes);


                mClusterManager.cluster();


            }


            String sensor = "sensor=false";
            String params = waypoints + coordenadas + "&" + sensor;
            String output = "json";
            String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
            ReadTask downloadTask = new ReadTask();
            downloadTask.execute(url);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public class MyClusterRenderer extends DefaultClusterRenderer<MyItem> {

        public MyClusterRenderer(Context context, GoogleMap map,
                                 ClusterManager<MyItem> clusterManager) {
            super(context, map, clusterManager);
        }

        @Override
        protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
            super.onBeforeClusterItemRendered(item, markerOptions);

            markerOptions.title(String.valueOf(item.getName()));

        }

        @Override
        protected void onClusterItemRendered(MyItem clusterItem, Marker marker) {
            super.onClusterItemRendered(clusterItem, marker);

        }

        @Override
        protected boolean shouldRenderAsCluster(Cluster<MyItem> cluster) {
            return cluster.getSize() > 10;
        }


    }



    public void startDemo() {


        mClusterManager = new ClusterManager<MyItem>(MapaViagem.this, googleMap);
//      mClusterManager.setAlgorithm(new NonHierarchicalDistanceBasedAlgorithm<MyItem>());


        mClusterManager.setRenderer(new MyClusterRenderer(MapaViagem.this, googleMap, mClusterManager));


        googleMap.setOnCameraChangeListener(mClusterManager);
        googleMap.setOnMarkerClickListener(mClusterManager);

        mClusterManager.setOnClusterClickListener(this);

        mClusterManager.setOnClusterItemClickListener(this);


    }


    private class ReadTask extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(MapaViagem.this);
            // setup your dialog here
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setMessage("Traçando Rotas");
            dialog.setCancelable(true);
            dialog.show();
        }


        @Override
        protected String doInBackground(String... url) {

            String data = "";
            try {
                HttpConnection http = new HttpConnection();
                data = http.readUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new ParserTask().execute(result);


        }


    }

    private class ParserTask extends
            AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

        @Override
        protected List<List<HashMap<String, String>>> doInBackground(
                String... jsonData) {


            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                PathJSONParser parser = new PathJSONParser();
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
            ArrayList<LatLng> points = null;
            PolylineOptions polyLineOptions = null;

            // traversing through routes
            for (int i = 0; i < routes.size(); i++) {
                points = new ArrayList<LatLng>();
                polyLineOptions = new PolylineOptions();
                List<HashMap<String, String>> path = routes.get(i);

                for (int j = 0; j < path.size(); j++) {
                    HashMap<String, String> point = path.get(j);

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                }

                polyLineOptions.addAll(points);
                polyLineOptions.width(4);
                polyLineOptions.color(Color.BLUE);
            }

            googleMap.addPolyline(polyLineOptions);
            dialog.dismiss();
        }
    }


    @Override
    public boolean onClusterClick(Cluster<MyItem> cluster) {
        // Show a toast with some info when the cluster is clicked.
        String firstName = cluster.getItems().iterator().next().name;
        Toast.makeText(this, cluster.getSize() + " (including " + firstName + ")", Toast.LENGTH_SHORT).show();
        return true;
    }


    @Override
    public boolean onClusterItemClick(MyItem item) {
        return false;
    }


    private void addItems(List<LatLng> markers, List<String> nomes) {

        for (int i = 0; i < markers.size(); i++) {
            MyItem offsetItem = new MyItem(markers.get(i), nomes.get(i));

            mClusterManager.addItem(offsetItem);

        }


    }


    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }


}

编辑:

我正在寻找一个解决方案,我不需要将静态图像组导入到我的项目中。我试图使用谷歌的Dynamic icons

@Override
    protected void onBeforeClusterItemRendered(final MyItem item, final MarkerOptions markerOptions) {
        super.onBeforeClusterItemRendered(item, markerOptions);

        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    markerOptions.title(String.valueOf(item.getName()));
                    //markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
                    URL myurl = new URL("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=B%7CFF0000%7CCCCCCC");


                    Bitmap bmp = BitmapFactory.decodeStream(myurl.openConnection().getInputStream());
                    markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bmp));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Thread mythread = new Thread(runnable);
        mythread.start();
    }

1 个答案:

答案 0 :(得分:2)

简单方法是https://code.google.com/p/google-maps-icons/wiki/NumericIcons请点击此链接并使用图标,您只需要在需要时更改可绘制图像

    private void addMarkers() {
        if (googleMap != null) {

            final LatLng WALL_STREET = new LatLng(lat_map, lng_map);

            // marker using custom image
            googleMap.addMarker(new MarkerOptions()
                    .position(WALL_STREET)
                    .title(address_location)
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.drawable.ic_carmap)));

            googleMap
                    .setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
                        @Override
                        public void onInfoWindowClick(Marker marker) {

                            String uri = "geo:" + lat_map + "," + lng_map;
                            startActivity(new Intent(
                                    android.content.Intent.ACTION_VIEW, Uri
                                            .parse(uri)));

                        }
                    });

        }
    }