如何从 firebase 数据库为多个 Google 地图标记添加单独的名称和说明
How to add seperate Names and Descriptions for Multiple Google Maps markers from firebase database
我已经能够使用存储在 Firebase 实时数据库中的坐标在我的 Google 地图上添加多个标记,但当前的问题是我无法检索标记正确。最后一个标记的名称将分配给从数据库中检索到的所有标记。
我想要的是每个标记都有一个单独的名称和(描述)分配给它。
分享了 output and firebase database as well.
的屏幕截图
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;
}
}
}
}
The name of the last marker gets assigned to all the markers that are retrieved from the database.
发生这种情况是因为您使用以下方法为所有标记设置了相同的名称:
options.title(Names2);
由于您是在循环中执行此操作,因此在循环结束时,Names2
将保留最后一个元素的值,因此会出现这种行为。要解决这个问题,您应该根据每个列表中的位置设置标题。这可以像这样简单地完成:
int position = 0; // Initialised the counter.
for (LatLng point : latlngs) {
options.position(point);
options.title(Names.get(position)); // Set the title according to the position.
options.snippet("someDesc");
mMap.addMarker(options);
position++; // Increment the position
}
我已经能够使用存储在 Firebase 实时数据库中的坐标在我的 Google 地图上添加多个标记,但当前的问题是我无法检索标记正确。最后一个标记的名称将分配给从数据库中检索到的所有标记。
我想要的是每个标记都有一个单独的名称和(描述)分配给它。
分享了
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;
}
}
}
}
The name of the last marker gets assigned to all the markers that are retrieved from the database.
发生这种情况是因为您使用以下方法为所有标记设置了相同的名称:
options.title(Names2);
由于您是在循环中执行此操作,因此在循环结束时,Names2
将保留最后一个元素的值,因此会出现这种行为。要解决这个问题,您应该根据每个列表中的位置设置标题。这可以像这样简单地完成:
int position = 0; // Initialised the counter.
for (LatLng point : latlngs) {
options.position(point);
options.title(Names.get(position)); // Set the title according to the position.
options.snippet("someDesc");
mMap.addMarker(options);
position++; // Increment the position
}