How to add Google Maps marker from Firebase data? - java

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) {
}
});
}
}

Remove this line:
private GoogleMap mMap=((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

Related

How can my android app google maps draw tracks of my movements with gps on google map sdk

I want a tracking line behind my location pointer which is moving to draw a it, so that we can see the route the person takes
enter image description here
public class Activity2 extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationListener locationListener;
private LocationManager locationManager;
private final long MIN_TIME = 1000; // 1 second
private final long MIN_DIST = 5; //1 meters
private LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
com.example.employeetrackingstarter.databinding.ActivityMapsBinding 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);
mapFragment.getMapAsync(this);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
}
#Override
public void onMapReady(GoogleMap googleMap) {
locationListener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
googleMap.clear();
googleMap.addMarker(new MarkerOptions().position(latLng).flat(true).title("My Position").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker5)));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DIST, locationListener);
}
catch (SecurityException e){
e.printStackTrace();
}
}
Try to use polyline, and when your user change location, draw it. You can see video link. First position its place where you start and second place its you current location.

Have to close and relaunch app for correct location to be shown on map

When retrieving the post's location (Latitude and Longitude) from Firebase, the correct location is retrieved and the marker is placed in the correct spot only after stopping the app and relaunching it. Otherwise, I get the location of some other post...
Anyone can explain to me why that happens? So if I upload a new post and then try to open its location it won't give me back the correct location unless I stop the app and re-enter. If I do everything from one go it gives me the location of another post.
I'm thinking it's a problem I have with my Adapter because when I pull up the post from my ProfileFragment it gives me back the correct location always.
The way that I am transferring the postid from my PostAdapter.java class to my MapsActivityUser.class is by using Intent, so the correct post can be found in Firebase. How can I fix this issue, and more importantly why is it happening?
PostAdapter.java
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public Context mContext;
public List<Post> mPost;
public Post post;
public PostAdapter(Context mContext, List<Post> mPost) {
this.mContext = mContext;
this.mPost = mPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, parent, false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
post = mPost.get(position);
Glide.with(mContext).load(post.getPostimage())
.apply(new RequestOptions().placeholder(R.drawable.placeholderimg))
.into(holder.post_image);
if ("".equals(post.getText_location())) {
holder.text_location.setVisibility(View.GONE);
} else {
holder.text_location.setVisibility(View.VISIBLE);
holder.text_location.setText(post.getText_location());
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView text_location;
public ViewHolder(#NonNull View itemView) {
super(itemView);
text_location = itemView.findViewById(R.id.text_location);
text_location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MapsActivityUser.class);
intent.putExtra("postid", post.getPostid());
mContext.startActivity(intent);
}
});
}
}
}
MapsActivityUser.java
public class MapsActivityUser extends FragmentActivity implements OnMapReadyCallback {
String postid;
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_user);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
postid = getIntent().getStringExtra("postid");
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
if (post != null) {
double latitude = post.getLocation().getLatitude();
double longitude = post.getLocation().getLongitude();
LatLng location = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(location).title("Event location"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 10));
} else {
Toast.makeText(MapsActivityUser.this, "Event doesn't have location on map", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
MapsActivityuser.java updated code with RecyclerView
public class MapsActivityUser extends FragmentActivity implements OnMapReadyCallback {
String postid;
private GoogleMap map;
private RecyclerView mRecyclerView;
private PostAdapter mPostAdapter;
private List<Post> mPostList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_user);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
postid = getIntent().getStringExtra("postid");
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mPostList = new ArrayList<>();
mPostAdapter = new PostAdapter(this, mPostList, postid);
mRecyclerView.setAdapter(mPostAdapter);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postid).child("location");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
double latitude = dataSnapshot.child("latitude").getValue(Double.class);
double longitude = dataSnapshot.child("longitude").getValue(Double.class);
LatLng location = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(location).title("Event location"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 10));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onPostClick(int position) {
//
}
}
Your approach is so wrong. Think about what's happening under the hood. Each time your adapter's onBindViewHolder() method is called and post = mPost.get(position); is executed that is the post is updated at each call. That's why yo're not getting correct post ids.
You probably don't want to set the post to the last and only value updated by the call of onBindViewHolder() each time.
I assume what you want is some sort of text_field to display the location of your posts, depending on which is clicked.
Your position variable is really messed up and that is not the correct position, instead you should use getAdapterPosition().

G Maps Android Java, last known location marker color different from Marker for location changed,but showing same marker color on running app

//do focus on the last else block of the code and the OnLocationChanged method(which is inside of the
OnMapReady() method)
this else block(contains the code fo rthe lastknown location method) and the onLocationChanged method
contains the code for the location which is being changed (here by passing from the extended controls
avaialable with the emulator,ie the box opens on clicking the downmost option in the emulator.)
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
LocationManager locationManager;
LocationListener locationListener;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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) {
mMap = googleMap;
locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener=new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mMap.clear();
LatLng place = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(place).title("Marker in Sydney").icon(BitmapDescriptorFactory.defaultMarker(HUE_YELLOW)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place));
mMap.animateCamera(CameraUpdateFactory.zoomTo(3));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
// Add a marker in Sydney and move the camera
if(Build.VERSION.SDK_INT<23)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}else
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
else
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastknownlocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng position=new LatLng(lastknownlocation.getLatitude(),lastknownlocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title("The Location is"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
}
}
}
Add the yellow icon to your second marker just like you did with the first one, like this:
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastknownlocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng position = new LatLng(lastknownlocation.getLatitude(), lastknownlocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title("The Location is").icon(BitmapDescriptorFactory.defaultMarker(HUE_YELLOW)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
}
Screenshot:
Hope this helps!

makers are calling the same activity on google maps

I have a little problem with applying makers on Google maps to call activities.
I can successfully create the points and even call the activitys by clicking them, but the problem is that they are always calling the same activity no matter what I do.
Can someone help me?
Already tried to move the variables, already tried to move the celula01 variable to see makes a connection, but none of this gives any return.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap, mCel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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(GoogleMap googleMap) {
mMap = googleMap;
mCel = googleMap;
LatLng celula04 = new LatLng(-23.174601, -45.839513);
mCel.addMarker(new MarkerOptions().position(celula04).title("Célula da Maria"));
mCel.moveCamera(CameraUpdateFactory.newLatLng(celula04));
mCel.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener(){
#Override
public boolean onMarkerClick(Marker marker) {
Intent intent = new Intent(MapsActivity.this, Celula02.class);
startActivity(intent);
return false;
}
});
LatLng celula01 = new LatLng(-23.173300, -45.821273);
mMap.addMarker(new MarkerOptions().position(celula01).title("Célula do Rafael"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(celula01));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener(){
#Override
public boolean onMarkerClick(Marker marker) {
Intent intent = new Intent(MapsActivity.this, Celula01.class);
startActivity(intent);
return false;
}
});
}
}
Thanks.
public class MapsActivity extends FragmentActivity implements
OnMarkerClickListener,
OnMapReadyCallback {
private static final LatLng celula04 = new LatLng(-23.174601, -45.839513);
private static final LatLng celula01 = new LatLng(-23.173300, -45.821273);
private Marker mcelula04;
private Marker mcelula01;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marker_demo);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/** Called when the map is ready. */
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Add some markers to the map, and add a data object to each marker.
mcelula04 = mMap.addMarker(new MarkerOptions()
.position(celula04)
.title("Célula da Maria");
mcelula04.setTag(1);
mcelula01 = mMap.addMarker(new MarkerOptions()
.position(celula01)
.title("Célula do Rafael");
mcelula01.setTag(2);
// Set a listener for marker click.
mMap.setOnMarkerClickListener(this);
}
/** Called when the user clicks a marker. */
#Override
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
Integer click = (Integer) marker.getTag();
// Check if a click count was set, then display the click count.
if (click = 1) {
public boolean onMarkerClick(Marker marker) {
Intent intent = new Intent(MapsActivity.this, Celula02.class);
startActivity(intent);
}elseif(click = 2){
Intent intent = new Intent(MapsActivity.this, Celula01.class);
startActivity(intent);
}
// Return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
}

How can I retrieve data from my Firebase Database to display markers?

I am trying to retrieve the latitude and longitude from my Firebase Database but I have difficulties doing it. As you can see under the screenshot, each photos have their own ID which are attached to a user ID. I want to display on a map with a marker all the locations from the database. Attached to this are my code and a screenshot of my database.
Database screenshot:
EDIT: I added more of my code as requested.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener, GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
private ChildEventListener mChildEventListener;
private DatabaseReference mUsersDataRef;
private DatabaseReference mPhotosDataRef;
private Map<String, User> mUsers = new HashMap<>(); //Map<(String) user-id, (User) user>
private List<Photo> mPhotos = new ArrayList<>();
private boolean usersFetched;
private boolean photosFetched;
private String photo_id;
Marker marker;
Part 2
#Override
protected void onCreate(Bundle savedInstanceState) {
FirebaseApp.initializeApp(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
ChildEventListener mChildEventListener;
mUsersDataRef = FirebaseDatabase.getInstance().getReference("photo_id");
mPhotosDataRef = FirebaseDatabase.getInstance().getReference("users");
mUsersDataRef.push().setValue(marker);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.setOnMarkerClickListener(this);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mPhotosDataRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()) {
User user = s.getValue(User.class);
mUsers.put(user.getUser_id(), user);
}
usersFetched = true;
doneLoading();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mPhotosDataRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()) {
Photo photo = s.getValue(Photo.class);
mPhotos.add(photo);
}
photosFetched = true;
doneLoading();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void doneLoading() {
if (usersFetched && photosFetched) {
for (Photo photo : mPhotos) {
User thisPhotosUser = mUsers.get(photo.getUser_id());
LatLng location=new LatLng(user.latitude,user.longitude);
mMap.addMarker(new MarkerOptions().position(location).title(user.name)).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
}
}
}
//#Override
public String getPhoto_id() {
return photo_id;
}
}
Try using Data Snapshot. The code can be modified in this way:
if (usersFetched && photosFetched) {
for (Photo photo : mPhotos) {
User thisPhotosUser = mUsers.get(photo.getUser_id());
thisPhotoUser.addListenerForSingleValueEvent(new ValueEvent Listner()){
public void onDataChange(DataSnapshot datasnapshot){
for(Datasnapshot photos : dataSnapshot.getChildren()){
if(photos.child(thisPhotoUser.exists())){
LatLng location = new LatLng(mPhotosDataRef.child(getPhoto_id(isChild(latitude))),user.longitude);
mMap.addMarker(newMarkerOptions().position(location).title(photo.name)).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
}
}
}
}
}
}

Categories