See the marker on the map - java

Create model for my marker:
public class FirebaseMarker {
public String dob;
public String dod;
public String name;
public double latitude;
public double longitude;
public FirebaseMarker() {
}
public FirebaseMarker(String name, double latitude, double longitude, String dob, String dod) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.dob = dob;
this.dod = dod;
}
Also create getters and setters for all this parametrs, after this i created class MapActivity(this activity i open when press on item in my recyclerView)
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
ChildEventListener mChildEventListener;
DatabaseReference mProfileRef = FirebaseDatabase.getInstance().getReference("Profile");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
createMapView();
FirebaseMarker marker = new FirebaseMarker("Lincoln", -34.506081, 150.88104, "24/12/1940", "02/07/2016");
FirebaseMarker marker2 = new FirebaseMarker("Lincoln", -35.506081, 140.88104, "24/12/1940", "02/07/2016");
mProfileRef.push().setValue(marker);
mProfileRef.push().setValue(marker2);
}
private void createMapView() {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
});
LatLng wollongong = new LatLng(-34.404336, 150.881632);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(wollongong, 18));
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
addMarkersToMap(googleMap);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
googleMap.setMyLocationEnabled(true);
}
#Override
public void onStop() {
if (mChildEventListener != null)
mProfileRef.removeEventListener(mChildEventListener);
super.onStop();
}
private void addMarkersToMap(GoogleMap googleMap) {
mChildEventListener = mProfileRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
FirebaseMarker marker = dataSnapshot.getValue(FirebaseMarker.class);
double latitude = marker.getLatitude();
double longitude = marker.getLongitude();
String name = marker.getName();
LatLng location = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(location).title(name));
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
But when i open the activity i see just a map, how i can see the marker?

You Define Variable
GoogleMap googleMap;
and in
public void onMapReady(GoogleMap googleMap)
they are the same
so what about try to rename it
so
GoogleMap MgoogleMap;
and edit onMapReady
public void onMapReady(GoogleMap googleMap) {
MgoogleMap =googleMap
addMarkersToMap(MgoogleMap );
}

Related

How to retrieve data from firebase for if else condition in java

I tried to make a different condition based on firebase database data. for example if the "Status" field data has value "Aktif" then the marker color will change to blue and when the "Status" value change into "Nonaktif" then the marker color will change into red. I already to use this code, but when tried to run it have the problem "error: incompatible types: cannot be converted to Context".
So how can i fix this problem? i will put the database structure here Firebase structure
private NavigationView navigationView;
private TextView namapengguna, emailpengguna;
private ImageView imageView2;
private View headerView;
DrawerLayout drawerLayout;
MapView mapView;
public MapboxMap mapboxMap;
private LocationManager manager;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
Marker myMarker;
private final int MIN_TIME = 1000;
private final int MIN_DISTANCE = 1;
private FirebaseUser user;
private DatabaseReference root;
private StorageReference reference;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoiaGFuZGlrYW1lZGlhbWFydGEiLCJhIjoiY2ttb2o1MWQ2MHp5cDJ3bHcyM3RkN2VvdiJ9.VOmbzomxo3nMMWLcmF2l0g");
setContentView(R.layout.activity_dashboard);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
mapView = (MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
namapengguna = (TextView) headerView.findViewById(R.id.namalengkap);
emailpengguna = (TextView) headerView.findViewById(R.id.emailpengguna);
imageView2 = findViewById(R.id.imageview2);
imageView2 = (ImageView) headerView.findViewById(R.id.imageview2);
user = FirebaseAuth.getInstance().getCurrentUser();
root = FirebaseDatabase.getInstance().getReference();
reference = FirebaseStorage.getInstance().getReference();
userID = user.getUid();
root.child("Users").child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userProfile = snapshot.getValue(User.class);
if (userProfile != null) {
String fullName = userProfile.fullname;
String email = userProfile.email;
namapengguna.setText(fullName);
emailpengguna.setText(email);
if (snapshot.hasChild("image")){
String image2 =snapshot.child("image").getValue().toString();
Picasso.get().load(image2).into(imageView2);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Dashboard.this, "Terjadi Kesalahan Pada Database", Toast.LENGTH_LONG).show();
}
});
}
public void ClickMenu(View view) {
openDrawer(drawerLayout);
}
public static void openDrawer(DrawerLayout drawerLayout) {
drawerLayout.openDrawer(GravityCompat.START);
}
public void ClickLogo(View view) {
closeDrawer(drawerLayout);
}
public static void closeDrawer(DrawerLayout drawerLayout) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
}
public void ClickHome(View view) {
recreate();
}
public void ClickUtama(View view) {
redirectActivity(this, Utama.class);
}
public void ClickAboutUs(View view) {
redirectActivity(this, AboutUs.class);
}
public void ClickLogout(View view) {
logout(this);
}
public static void logout(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Logout");
builder.setMessage("Are you sure want to logout?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
activity.finishAffinity();
System.exit(0);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
public static void redirectActivity(Activity activity, Class aClass) {
Intent intent = new Intent(activity, aClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
root.child("otoped").addValueEventListener(new ValueEventListener() {
Query q = FirebaseDatabase.getInstance().getReference("otoped").orderByChild("Status").equalTo("0");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyLocation location = dataSnapshot.getValue(MyLocation.class);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng loc = new LatLng(latitude,longitude);
if (q != null){
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_markerbiru)));
myMarker.setPosition(loc);
}else{
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.markerblue)).position(loc).title("Otoped1"));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
Drawable drawable = ResourcesCompat.getDrawable(getResources(),R.drawable.ic_baseline_location_on_24,null);
Bitmap mBitmap = BitmapUtils.getBitmapFromDrawable(drawable);
}
});
}
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(Dashboard.this)){
LocationComponent locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(Dashboard.this, loadedMapStyle).build());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
return;
}
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager((PermissionsListener) this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
closeDrawer(drawerLayout);
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLocationChanged(#NonNull Location location) {
if (location != null){
saveLocation(location);
}else {
Toast.makeText(this, "No Location", Toast.LENGTH_SHORT).show();
}
}
private void saveLocation(Location location) {
root.child("otoped").setValue(location);
}
}
I Got problem when tried to edit this code
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
root.child("otoped").addValueEventListener(new ValueEventListener() {
Query q = FirebaseDatabase.getInstance().getReference("otoped").orderByChild("Status").equalTo("0");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyLocation location = dataSnapshot.getValue(MyLocation.class);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng loc = new LatLng(latitude,longitude);
if (q != null){
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_markerbiru)));
myMarker.setPosition(loc);
}else{
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.markerblue)).position(loc).title("Otoped1"));
}
}

Cannot assign local value to global value

I am just a beginner in java/android. I was trying to pass location latitude and longitude to firebase. So I toast the message to see the value it was showing 0.0. I passed lat and long value from client.getlastlocation to the global value of lat and lon, but it is showing default value 0.0, why is this happening?
public class shopaction extends Fragment implements CompoundButton.OnCheckedChangeListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Location location;
GoogleApiClient googleApiClient;
FusedLocationProviderClient client;
private String mParam1;
private String mParam2;
String s;
Switch action;
public double lat,lon;
private OnFragmentInteractionListener mListener;
public shopaction() {
}
public static shopaction newInstance(String param1, String param2) {
shopaction fragment = new shopaction();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_shopaction, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
action = (Switch) view.findViewById(R.id.action);
action.setOnCheckedChangeListener(this);
client = LocationServices.getFusedLocationProviderClient(getActivity());
Button button=(Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
}
});
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
DatabaseReference databaseReference=firebaseDatabase.getReference();
databaseReference.child("shop").child("location").setValue(lat);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(action.isChecked())
{
Toast.makeText(getActivity(),"Your shop is open",Toast.LENGTH_LONG).show();
action.setText("open");
s="open";
}
else
{
Toast.makeText(getActivity(),"Your shop is closed",Toast.LENGTH_LONG).show();
action.setText("close");
s="close";
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The problem is that getLastLocation() returns a Task which then operates asynchronously. The location data are not available until the success listener call-back has actually been called. Meanwhile, your code proceeds to display a Toast using the current (default) values of 0 for lat and lon.
One way to fix this is to have your success listener callback display the toast, rather than your main code. So instead of this:
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
// Firebase update code that depends on location data
use this:
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
// Firebase update code that depends on location data
}
});

Broadcast Receiver from Service in MainActivity / MapsActivity

I have a service, which get the current position every Second and then the Service should send the location with an Broadcast back to the Main Activity.
With the log i can see, that the Service Class sends the Broadcast, but the MainActivity never get it.
My Service:
public class MyService extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10;
private void sendLocation(Location l) {
Intent intent = new Intent("GPSLocationUpdates");
// You can also include some extra data.
intent.putExtra("Lat", l.getLatitude());
intent.putExtra("Lon", l.getLongitude());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.e(TAG, l + "gesendet!");
}
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
Toast.makeText(MyService.this, "ja", Toast.LENGTH_LONG).show();
sendLocation(location);
mLastLocation.set(location);
}
[...]
}
}
The MainActicity (with Map included):
public class MainActivity extends AppCompatActivity
implements OnMapReadyCallback,
NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "Location";
private GoogleMap mMap;
private final static int MY_PERMISSIONS_FINE_LOCATION = 123;
track track = new track();
private BroadcastReceiver locationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive");
String action = intent.getAction();
LatLng pos = new LatLng(intent.getDoubleExtra("Lat", 0),
intent.getDoubleExtra("Lon", 0));
Log.e(TAG, "Position: " + pos + "empfangen");
track.posAdd(pos);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver(locationReceiver,
new IntentFilter("GPSLocationUpdates"));
Log.i(TAG, "BroadcastManager erstellt");
setContentView(R.layout.activity_main);
// Obtain the SupportMapFragment and get notified when the map is ready
to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
[...]
}
public void onMapReady(GoogleMap googleMap) {
[...]
startService(new Intent(this, MyService.class));
}
#Override
public void onRequestPermissionsResult(int requestCode, String
permissions[], int[] grantResults) {....}
public void onBackPressed() {...}
#Override
public boolean onCreateOptionsMenu(Menu menu) {...}
#Override
public boolean onOptionsItemSelected(MenuItem item) {...}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {...}
}
Hopefully you can help

how to determine current localization and add marker to GoogleMapsApi in android

I can't resolve this problem. I trying to create Fragment with a map and I have this done. When I add static Long, Lat value the map show this o a map, But when I trying to make it automatic with getting localization in runnable the application just open the map and don't show specific LongLand values.
How to do this?
For getting long and late I'm using LocalizationManager, of course, I add permissions in manifest and also check runtime
public class LocalizationFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap map;
MapView mapView;
View mview;
private double latitude, longtitude;
private Handler handler;
private Runnable runnable;
public LocalizationFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mview = inflater.inflate(R.layout.fragment_localization, container, false);
handler = new Handler();
getLocation();
if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 13);
}
if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 11);
}
return mview;
}
#OnClick(R.id.button)
public void buttonStart() {
getLocation();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) mview.findViewById(R.id.mapView);
if (mapView != null) {
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
}
}
private void getLocation() {
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
};
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
map = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
runnable = new Runnable() {
#Override
public void run() {
getLocation();
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longtitude)).title("Statue").snippet("Something"));
CameraPosition liberty = CameraPosition.builder().target(new LatLng(latitude, longtitude)).zoom(15).bearing(0).tilt(45).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
handler.postDelayed(this, 5000);
}
};
}
}
You need to add markers form the main thread.add this to your runnable.
runOnUiThread(new Runnable() {
#Override
public void run() {
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longtitude)).title("Statue").snippet("Something"));
}
});
I think this problem come from synchronize data. If you got location after add marker, it is meaningless, you get no location, and you have no marker on map, try to move action add marker into onLocationChanged

Cannot get markers from Firebase

I cannot get markers on my map from Firebase. I have tried a few examples I found but I can't seem to get it to work. I want all of the locations that I have stored in FireBase to be on one map.
Code:
public class AllJobsMapActivity extends FragmentActivity implements OnMapReadyCallback {
private DatabaseReference geoDatabase = FirebaseDatabase.getInstance().getReference("places");
GoogleMap mapFragment;
List<Marker> markerList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_job_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
geoDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.child("places").getChildren()) {
String latitude = child.child("lattitude").getValue().toString();
String longitude = child.child("longitude").getValue().toString();
double Latitude = Double.parseDouble(latitude);
double Longitude = Double.parseDouble(longitude);
String name = child.child("name").getValue().toString();
LatLng cod = new LatLng(Latitude, Longitude);
googleMap.addMarker(new MarkerOptions().position(cod).title(name));
}
}
#Override
public void onCancelled(DatabaseError firebaseError) {
}
});
}
}
Firebase Tree:

Categories

Resources