добавить ArrayList маркеров на карту Google - PullRequest
0 голосов
/ 09 мая 2018

Я пытаюсь отобразить несколько маркеров на карте Google, но мне кажется, что отображается только последний. Причина в том, что маркеры перезаписываются в цикле for. Я создал ArrayList, в котором будут храниться маркеры, но я не знаю, как добавить его на карту Google.

библиотека полилиний содержит метод под названием addAll, который добавляет массив полилиний, но у маркеров такого нет. Может ли кто-нибудь предложить способ добавить несколько маркеров на карту?

   public void mapForGPS(GoogleMap googleMap) {
        mMap = googleMap;
        double[] firstCoords;
        double[] lastCoords;
        double[] receivedDataArray;
        double latitude;
        double longitude;

        double[] firstSetOfCoordinatesFromArray;
        double[] lastSetOfCoordinatesFromArray;

        double[] tempCoordinatesArray;
        String[] tempDurationAndTimeArray;
        String time;
        GpsData gpsDataObj;

        String[] dataForOneGreenDot;

        String[] arrayOfGreenDots = new String[3];

        // this will store coordinates for one iteration of a selected day
        ArrayList<LatLng> coordList = new ArrayList<LatLng>();

        ArrayList<String[]> arrayListOfGreenDots = new ArrayList<String[]>();

        // clear polyline array that has coordinates form previous iteration
        coordList.clear();

        // clears all the markers on the map for the next iteration
        mMap.clear();

        // loop through JSON array of coordinates and assign data into a coordinates array with an
        // object of Latitude and Longitude
        for (int i = 0; i <= arrayOfGpsData.size() - 1; i++) {
            gpsDataObj = arrayOfGpsData.get(i);

            tempCoordinatesArray = gpsDataObj.getArrayOfDoubles();
            tempDurationAndTimeArray = gpsDataObj.getArrayOfStrings();

            latitude = tempCoordinatesArray[0];
            longitude = tempCoordinatesArray[1];
            coordList.add(new LatLng(latitude,longitude));

            time = tempDurationAndTimeArray[0];

            String latString = String.valueOf(latitude);
            String longString = String.valueOf(longitude);

            arrayOfGreenDots[0] = latString;
            arrayOfGreenDots[1] = longString;
            arrayOfGreenDots[2] = time;

            arrayListOfGreenDots.add(arrayOfGreenDots);
        }

        // if there was a previous polyline on the map, clear it
        if(polylineGPS != null){
            polylineGPS.remove();
        }

        // add coordinates to a polylineGPS object
        options = new PolylineOptions().addAll(coordList).width(5).color(Color.BLUE).geodesic(true);
        polylineGPS = mMap.addPolyline(options);


        // if user selected date in date-time picker then marker will point to
        // first set of coordinates in the coordinatesArray and the map will zoom in on that point
        if(!arrayOfGpsData.isEmpty())
        {
            double[] coordinatesFromFirstIndex = new double[2];
            String[] timeAndDurationFromFirstIndex = new String[2];

            double[] coordinatesFromLastIndex = new double[2];
            String[] timeAndDurationFromLastIndex = new String[2];

            GpsData objectDataFromFirstIndex = new GpsData(coordinatesFromFirstIndex, timeAndDurationFromFirstIndex);
            GpsData objectDataFromLastIndex = new GpsData(coordinatesFromLastIndex, timeAndDurationFromLastIndex);

            // get first set of coordinates from array as starting position
            objectDataFromFirstIndex = arrayOfGpsData.get(0);
            firstSetOfCoordinatesFromArray = objectDataFromFirstIndex.getArrayOfDoubles();

            // get last set of coordinates from array as ending position
            objectDataFromLastIndex = arrayOfGpsData.get(arrayOfGpsData.size() - 1);
            lastSetOfCoordinatesFromArray = objectDataFromLastIndex.getArrayOfDoubles();

            //timeAndDurationFromFirstIndex = objectDataFromFirstIndex.getArrayOfStrings();

            // place marker for starting position
            LatLng firstLocationPointOfDevice = new LatLng(firstSetOfCoordinatesFromArray[0], firstSetOfCoordinatesFromArray[1]);
            mMap.addMarker(new MarkerOptions().position(firstLocationPointOfDevice).icon((BitmapDescriptorFactory.fromResource(R.drawable.blue_marker))).title("Starting Location"));

            // place marker for ending position
            LatLng lastLocationPointOfDevice = new LatLng(lastSetOfCoordinatesFromArray[0], lastSetOfCoordinatesFromArray[1]);
            mMap.addMarker(new MarkerOptions().position(lastLocationPointOfDevice).icon(BitmapDescriptorFactory.fromResource(R.drawable.pink_marker)).title("Ending Location"));

            // zoom in on first set of coordinates form coordinatesArray
            mMap.moveCamera(CameraUpdateFactory.newLatLng(firstLocationPointOfDevice));

            // camera zoom in position
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(firstLocationPointOfDevice, 10));

            List<Marker> markers = new ArrayList<Marker>();

            // adding markers to array list
            for(int k = 0; k <= arrayListOfGreenDots.size() - 1; k++){
                dataForOneGreenDot = arrayListOfGreenDots.get(k);

                double latSingle = Double.parseDouble(dataForOneGreenDot[0]);
                double longSingle = Double.parseDouble(dataForOneGreenDot[1]);
                String timeSingle = dataForOneGreenDot[2];

                //drawMarker(latSingle, longSingle, timeSingle);
                LatLng greenDot = new LatLng(latSingle, longSingle);
                marker = mMap.addMarker(new MarkerOptions().position(greenDot).icon(BitmapDescriptorFactory.fromResource(R.drawable.green_dot)).title(timeSingle));

                markers.add(marker);
            }
        }
        // if user did not select any date from date time picker, then by default the map will zoom on vancouver
        else if(arrayOfGpsData.isEmpty())
        {
            // default location if no date is selected
            LatLng defaultLocation = new LatLng(49.2827, -123.1207);
            mMap.moveCamera(CameraUpdateFactory.newLatLng(defaultLocation));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(defaultLocation, 10));
        }
    }

1 Ответ

0 голосов
/ 11 мая 2018

Я действительно не знаю, почему этот вопрос был отвергнут, потому что он затрагивает законную проблему, на которую не было немедленного ответа.

Я нашел решение, хотя:

for (int i = 0; i <= arrayOfGpsData.size() - 1; i++) {
            gpsDataObj = arrayOfGpsData.get(i);

            tempCoordinatesArray = gpsDataObj.getArrayOfDoubles();
            tempDurationAndTimeArray = gpsDataObj.getArrayOfStrings();

            latitude = tempCoordinatesArray[0];
            longitude = tempCoordinatesArray[1];

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

            time = tempDurationAndTimeArray[0];

            mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude))
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.green_dot_6px))
                    .title(time)
            );
        }

Когда я перебираю свой arrayOfGpsData и назначаю lat и long моему LatLng объекту, я сразу добавляю маркер к этому LatLng с отметкой времени.

Надеюсь, это поможет кому-то в будущем: D

...