Home > Enterprise >  How to add seperate Names and Descriptions for Multiple Google Maps markers from firebase database
How to add seperate Names and Descriptions for Multiple Google Maps markers from firebase database

Time:02-17

I've been able to add multiple markers on my Google Maps using the coordinates that are stored in the Firebase Realtime Database but the current problem is that I'm not able to retrieve the names of the markers properly. The name of the last marker gets assigned to all the markers that are retrieved from the database.

What I want is that every marker gets a separate name and (description) assigned to it. Shared a screenshot of the Outputoutput and firebase database as well.enter image description here

public class HistoricalMapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int REQUEST_LOCATION_PERMISSION = 1009;
    private GoogleMap mMap;
    private ActivityMapsBinding binding;

    //update--Taking multiple markers from Realtime Database
    private MarkerOptions options = new MarkerOptions();
    private ArrayList<LatLng> latlngs = new ArrayList<>();
    private ArrayList<String> Names = new ArrayList<>();
    String Lat ,Lon,Names1, Names2;
    double latitude , longitude;
    //update--Taking multiple markers from Realtime Database

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


        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);




        //update--Taking multiple markers from Realtime Database
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("Positions");
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot chidSnap : dataSnapshot.getChildren()) {

                    Lat = String.valueOf(chidSnap.child("Latitude").getValue());
                    Lon = String.valueOf(chidSnap.child("Longitude").getValue());
                   // Names1 = String.valueOf(chidSnap.getKey());

                    //Getting Value of Name of the Place
                    Names1 = String.valueOf(chidSnap.child("Name").getValue());

                    latitude= Double.parseDouble(Lat);
                    longitude= Double.parseDouble(Lon);
                    Names2 = Names1;

                    latlngs.add(new LatLng(latitude, longitude));
                    Names.add(Names2);

                }
                if(mMap != null) {
                    for (LatLng point : latlngs) {
                        options.position(point);
                        options.title(Names2);
                        options.snippet("someDesc");
                        mMap.addMarker(options);
                    }
                }

            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
        //update--Taking multiple markers from Realtime Database

        mapFragment.getMapAsync(this);
    }



    private void addMapMarkers(){

    }


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

        //update--Taking multiple markers from Realtime Database
        for (LatLng point : latlngs) {
            options.position(point);
            options.title(Names1);
            options.snippet("someDesc");
            googleMap.addMarker(options);
        }
        //update--Taking multiple markers from Realtime Database


        //Adding custom maps style over here
        //******** THIS PART OF CODE EXCLUSIVELY DESIGNED TO FETCH THE CUSTOM MAPS.JSON TEMPLATE**********
        enableMyLocation();

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.mapstyle));
            if (!success) {
                Log.e("MapsActivity", "Style parsing failed.");
            }
        } catch (Resources. NotFoundException e) {
            Log.e("MapsActivity", "Can't find style. Error: ", e);
        }
        //******** MAP STYLING CODE ENDS OVER HERE **********



/*        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        LatLng islamabad = new LatLng(33.68, 73.04);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Islamabad"));
        //moving the camera position to Islamabad.
        mMap.moveCamera(CameraUpdateFactory.newLatLng(islamabad));*/


    }

    //Getting the Users current Location

    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            ActivityCompat.requestPermissions(this, new String[]
                            {Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        // Check if location permissions are granted and if so enable the
        // location data layer.
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_LOCATION_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    enableMyLocation();
                    break;
                }
        }
    }
}

CodePudding user response:

The name of the last marker gets assigned to all the markers that are retrieved from the database.

This is happening because you are setting the same name for all markers using:

options.title(Names2);

Since you are doing that in a loop, by the time it ends, Names2 will hold the value of the last element, hence that behavior. To solve this, you should set the title according to the position of each in the list. This can be simply done like this:

int position = 0; //           
  • Related