简体   繁体   中英

How to add Google Maps marker from Firebase data?

I'm trying to create a map that loads markers from Firebase.

I've divided the position code to 2 different code: location_left and location_right.

It means that a normal Marker line will look like this:

 LatLng cod = new LatLng(location_left, location_right);
                googleMap.addMarker(new MarkerOptions().position(cod).title(party_title));

But it doesn't work. The application crashes.

This is the code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private static final String FIREBASE_URL="https://haerev.firebaseio.com/";
    private Firebase firebaseRef;
    private GoogleMap mMap=((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps2);
        Firebase.setAndroidContext(this);
        firebaseRef = new Firebase(FIREBASE_URL);

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

    @Override
    public void onMapReady(final GoogleMap googleMap) {
        firebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot child : dataSnapshot.child("users").getChildren()) {
                    String rightLocation = child.child("location_right").getValue().toString();
                    String leftLocation = child.child("location_left").getValue().toString();

                    double location_left = Double.parseDouble(leftLocation);
                    double location_right = Double.parseDouble(rightLocation);
                    String party_title = child.child("party/party_title").getValue().toString();
                    LatLng cod = new LatLng(location_left, location_right);
                    googleMap.addMarker(new MarkerOptions().position(cod).title(party_title));
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });
    }
}

删除此行:

private GoogleMap mMap=((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM