I am trying to add markers for each driver in the driver model which is loaded into an array list. When I toast the result I get all the drivers but the marker shows only one driver.
Please help me get the markers for each driver in the module.
//Add markers for all drivers retrieved
private void addMarkers(List<Driver> drivers) {
if (map != null && !drivers.isEmpty()) {
for (int i = 0; i < drivers.size(); i++) {
//Get driver model
Driver driver = drivers.get(i);
Toast.makeText(this, driver.toString(), Toast.LENGTH_LONG).show();
//Add marker
GeoPoint driverLocation = driver.getGeoPoint();
if (driverMarker == null) {
driverMarker = map.addMarker(new MarkerOptions()
.title(driver.getCarNumber())
.position(new LatLng(driverLocation.getLatitude(), driverLocation.getLongitude()))
);
driverMarker.showInfoWindow();
}
else{
driverMarker.remove();
driverMarker = map.addMarker(new MarkerOptions()
.title(driver.getCarNumber())
.position(new LatLng(driverLocation.getLatitude(), driverLocation.getLongitude()))
);
driverMarker.showInfoWindow();
}
}
}
}
You're only get one marker because you're adding and removing the same Marker again and again in your code:
for (int i = 0; i < drivers.size(); i++) {
if (driverMarker == null) {
driverMarker = map.addMarker(...);
} else {
driverMarker.remove();
...
}
}
So, you need to slightly change your code to adding each marker and save it to a list. Something like this:
private void addMarkers(List<Driver> drivers) {
List<Marker> markers = new ArrayList<>();
if (map != null && !drivers.isEmpty()) {
for (int i = 0; i < drivers.size(); i++) {
//Get driver model
Driver driver = drivers.get(i);
//Add marker
GeoPoint driverLocation = driver.getGeoPoint();
Marker driverMarker = map.addMarker(new MarkerOptions()
.title(driver.getCarNumber())
.position(new LatLng(driverLocation.getLatitude(), driverLocation.getLongitude())));
driverMarker.showInfoWindow();
// add to the list
markers.add(driverMarker);
}
}
return markers;
}
then you can use the method to get the list of marker:
// assumet drivers is list of Driver
List<Marker> markers = addMarkers(drivers);
Related
I have googleMap (v2) with polyline that presents a route between the user current location and the destination point. Now, I want to update the polyline according to the user moving.
I tried to redrawing the whole polyline when location is changed but the polyline is flickering.
I didn't find any appropriate function in the PolylineOptions class (the function add() is only to add a vertex but not to update or remove)
do you have any idea how to update the polyline ???
thank you for giving your time.
The only way as of version 3.1.36:
List<LatLng> points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
Hopefully the API will be enhanced in later versions.
*I have already done working on updating polyline path without removing the polyline. We can do this by changing the points of that polyline. Check below code.
This is the logic of setting new points to polyline.
/*Here the routes contain the points(latitude and longitude)*/
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
Detail Explanation:
private GoogleMap map_object;
private Marker marker_driver;
private Marker marker_drop_off;
private Polyline polyline_path;
private PolylineOptions polylineOptions_path;
...
...
...
/*HelperDirectionFinder is a class that I create to call google API and I used this
class to get directions routes*/
/*I have created Service, and I'm calling this lines below after 5 sec. to get the
updated routes from google API.*/
HelperDirectionFinder directionFinder = new HelperDirectionFinder(
JobEndScreen.this, source, destinations);
try {
directionFinder.showDirection();
} catch (UnsupportedEncodingException e) {
HelperProgressDialog.closeDialog();
}
...
...
...
#Override
public void onDirectionFinderStart() {
if(polylineOptions_path == null){
HelperProgressDialog.showDialog(getActivity(), "", getString(R.string.text_loading));
}
}
/*This interface method is called after getting routes from google API.*/
/*Here the routes contains the list of path or routes returned by Google Api*/
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
HelperProgressDialog.closeDialog();
/*When polylineOptions_path is null it means the polyline is not drawn.*/
/*If the polylineOptions_path is not null it means the polyline is drawn on map*/
if(polylineOptions_path == null){
for (Route route : routes) {
polylineOptions_path = new PolylineOptions().
geodesic(true).
color(ContextCompat.getColor(getActivity(), R.color.color_bg_gray_dark)).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions_path.add(route.points.get(i));
polyline_path = map_object.addPolyline(polylineOptions_path);
}
}
else {
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
}
}
//Declare on global
PolylineOptions polyOptions, polyOptions2;
Polyline polyline2;
List<LatLng> ltln;
private Double lat_decimal = 0.0,lng_decimal=0.0;
//initialize
ltln = new ArrayList<>();
//if you are using routing library
compile 'com.github.jd-alexander:library:1.0.7'
#Override
public void onRoutingSuccess(ArrayList<Route> arrayList, int i) {
//Add this code snippet on onRoutingSuccess to store latlan list
ltln = new ArrayList<>();
System.out.println("-----arrayList------" + arrayList.get(0).getPoints());
ltln = arrayList.get(0).getPoints();
// NOTE here already we draw polyLine 1
}
//below mentioned how to update polyline
private void UpdatePoliline(){
System.out.println("-------runnablePolyline-------"+ltln.size());
try {
if (ltln.size() > 0) {
for (int i = 0; i < ltln.size(); i++) {
ltln.remove(i);
if (CalculationByDistance(ltln.get(i), new LatLng(lat_decimal, lng_decimal)) >= 10) {
break;
}
}
polyOptions2 = new PolylineOptions();
polyOptions2.color(getResources().getColor(R.color.app_color));
polyOptions2.width(7);
polyOptions2.addAll(ltln);
if (polyline2 == null) {
polyline2 = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline2);
if (polyline != null) {
polyline.remove();
polyline = null;
}
} else {
polyline = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline);
if (polyline2 != null) {
polyline2.remove();
polyline2 = null;
}
}
System.out.println("=====waypoints new===" + ltln);
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
// Calculating distance between 2 points
public float CalculationByDistance(LatLng StartP, LatLng EndP) {
Location locationA = new Location("Source");
locationA.setLatitude(StartP.latitude);
locationA.setLongitude(StartP.longitude);
Location locationB = new Location("Destination");
locationB.setLatitude(EndP.latitude);
locationB.setLongitude(EndP.longitude);
float distance = locationA.distanceTo(locationB);
return distance;
}
//Redraw Polyline vehicle is not in current polyline with particular distance
if (ltln.size() > 0) {
if (PolyUtil.isLocationOnPath(new LatLng(currentlat, currentLon), ltln, false, 60.0f) ){
System.out.println("===tolarance===" + true);
} else {
//Redraw Polyline
}
}
UpdatePoliline();
I am trying to add 2 markers to the google map with the following code. It shows only one location instead of two. Can anyone look at it and comment ? I saw that the location values are distinct with a debugger.
public void updateMapWithNewLocation() {
Marker marker1 = null;
Marker marker2 = null;
LatLng latLng1 = null;
LatLng latLng2 = null;
if (mMyLocation != null) {
latLng1 = new LatLng(mMyLocation.getLatitude(), mMyLocation.getLongitude());
MarkerOptions myMarkerOptions = new MarkerOptions()
.position(latLng1)
.title("me");
marker1 = mMap.addMarker(myMarkerOptions);
}
if (mFriendLocation != null) {
latLng2 = new LatLng(mMyLocation.getLatitude(), mMyLocation.getLongitude());
MarkerOptions friendMarkerOptions = new MarkerOptions()
.position(latLng2)
.title("friend");
marker2 = mMap.addMarker(friendMarkerOptions);
}
List<Marker> markerList = new ArrayList<>();
if(marker1 != null){
markerList.add(marker1);
}
if(marker2 != null) {
markerList.add(marker2);
}
zoomToShowAllMarkers(markerList);
}
private void zoomToShowAllMarkers(List<Marker> markers) {
if ( markers == null || markers.size() < 1)
return;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
for (Marker m : markers) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bounds.getCenter(), 10));
}
try using below code.
// Creating an instance of MarkerOptions
MarkerOptions markerOptions1 = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions1.position(LatLng1);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions1);
// Creating an instance of MarkerOptions
MarkerOptions markerOptions2 = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions2.position(LatLng2);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions2);
or you can add using loop inside the your custom method.
This is how I did to zoom with bounds:
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 20);
map.animateCamera(cameraUpdate);
}
});
The onMapLoaded() makes the zooming done after the map got loaded.
Hope this helps.
Thanks for your suggestions and looking at it.
I had a copy/paste error of using myLocation instead of friendLocation
this particular line:
latLng2 = new LatLng(mMyLocation.getLatitude() mMyLocation.getLongitude()); <-- should use mFriendLocation instead of mMyLocation.
Sorry for the trouble.
I've implemented a clustermarker in my app, I have a list of LatLng that comes from my database, now I want to show the name of the clients as title when the user clicks on the marker,but when I click on the marker it shows me nothing, how can I achieve that, this is my code so far:
public class MapaViagem extends FragmentActivity {
private GoogleMap googleMap;
private String rm_IdViagem;
private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ViagemModel mViagemModel = new ViagemModel();
private ClusterManager<MyItem> mClusterManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
try {
Bundle parametros = getIntent().getExtras();
rm_IdViagem = parametros.getString("id_viagem");
Repositorio ca = new Repositorio(this);
mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));
Repositorio cl = new Repositorio(this);
mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));
int i;
for ( i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
System.out.println("NOMES " + mClienteModel.get(i).getNome());
for (int j = 0; j < mEnderecoModel.size(); j++) {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
final float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
final float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
coordList.add(new LatLng(latitude, longitude));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 10));
// Initialize the manager with the context and the map.
// (Activity extends context, so we can pass 'this' in the constructor.)
mClusterManager = new ClusterManager<MyItem>(this, googleMap);
// Point the map's listeners at the listeners implemented by the cluster
// manager.
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
addItems(coordList);
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
LatLng pos = marker.getPosition();
int arryListPosition = getArrayListPosition(pos);
return true;
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private int getArrayListPosition(LatLng pos) {
for (int i = 0; i < mEnderecoModel.size(); i++) {
if (pos.latitude == Double.parseDouble(mEnderecoModel.get(i).getLatitude().split(",")[0])) {
if (pos.longitude == Double.parseDouble(mEnderecoModel.get(i).getLongitude().split(",")[1]))
return i;
}
}
return 0;
}
private void addItems(List<LatLng> markers) {
for (int i = 0; i < markers.size(); i++) {
MyItem offsetItem = new MyItem(markers.get(i));
mClusterManager.addItem(offsetItem);
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Not sure how you are initializing your Markers because you don't show that part of the code but put a title on it is done this way:
//You need a reference to a GoogleMap object
GoogleMap map = ... // get a map.
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183)) //Or whatever coordinate
.title("Your title")
.snippet("Extra info"));
And that's it, when you click it you'll see the info of that marker.
You can find more information here
EDIT
For the ClusterManagerI think you can find this answer helpful
I tried to draw a polyline between given markers, which are saved at an arraylist (poisMap). Based on my research I created the following code. I get no error and also no line, but the markers are all visible.
How have I to place the polyline method in order to get it working?
private void setUpMap() {
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
PolylineOptions routeDraw = new PolylineOptions().add(new LatLng(latitude,longitude)).width(5).color(Color.BLUE);
Polyline polyline = mMap.addPolyline(routeDraw);
}
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
private void setUpMap() {
PolylineOptions routeDraw = new PolylineOptions().width(5).color(Color.BLUE);
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
routeDraw.add(new LatLng(latitude,longitude))
}
Polyline polyline = mMap.addPolyline(routeDraw);
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
other
private void setUpMap() {
LatLng[] latlngarray = new LatLng[poisMap.size()];
for (int i = 0; i < poisMap.size(); i++) {
latitude = poisMap.get(i).getLatitudePoi();
if (latitude == 0) {
Log.i("debug", "latitude null");
}
longitude = poisMap.get(i).getLongitudePoi();
poiTitle = poisMap.get(i).getTitle();
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(poiTitle));
latlngarray[i]= new LatLng(latitude, longitude);
}
PolylineOptions routeDraw = new PolylineOptions().add(latlngarray).width(5).color(Color.BLUE);
Polyline polyline = mMap.addPolyline(routeDraw);
latitudeZoom = poisMap.get(0).getLatitudePoi();
longitudeZoom = poisMap.get(0).getLongitudePoi();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeZoom,longitudeZoom),14));
mMap.setMyLocationEnabled(true);
}
check this it is helpfull if you use google map
[http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/][1]
I have googleMap (v2) with polyline that presents a route between the user current location and the destination point. Now, I want to update the polyline according to the user moving.
I tried to redrawing the whole polyline when location is changed but the polyline is flickering.
I didn't find any appropriate function in the PolylineOptions class (the function add() is only to add a vertex but not to update or remove)
do you have any idea how to update the polyline ???
thank you for giving your time.
The only way as of version 3.1.36:
List<LatLng> points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
Hopefully the API will be enhanced in later versions.
*I have already done working on updating polyline path without removing the polyline. We can do this by changing the points of that polyline. Check below code.
This is the logic of setting new points to polyline.
/*Here the routes contain the points(latitude and longitude)*/
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
Detail Explanation:
private GoogleMap map_object;
private Marker marker_driver;
private Marker marker_drop_off;
private Polyline polyline_path;
private PolylineOptions polylineOptions_path;
...
...
...
/*HelperDirectionFinder is a class that I create to call google API and I used this
class to get directions routes*/
/*I have created Service, and I'm calling this lines below after 5 sec. to get the
updated routes from google API.*/
HelperDirectionFinder directionFinder = new HelperDirectionFinder(
JobEndScreen.this, source, destinations);
try {
directionFinder.showDirection();
} catch (UnsupportedEncodingException e) {
HelperProgressDialog.closeDialog();
}
...
...
...
#Override
public void onDirectionFinderStart() {
if(polylineOptions_path == null){
HelperProgressDialog.showDialog(getActivity(), "", getString(R.string.text_loading));
}
}
/*This interface method is called after getting routes from google API.*/
/*Here the routes contains the list of path or routes returned by Google Api*/
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
HelperProgressDialog.closeDialog();
/*When polylineOptions_path is null it means the polyline is not drawn.*/
/*If the polylineOptions_path is not null it means the polyline is drawn on map*/
if(polylineOptions_path == null){
for (Route route : routes) {
polylineOptions_path = new PolylineOptions().
geodesic(true).
color(ContextCompat.getColor(getActivity(), R.color.color_bg_gray_dark)).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions_path.add(route.points.get(i));
polyline_path = map_object.addPolyline(polylineOptions_path);
}
}
else {
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
}
}
//Declare on global
PolylineOptions polyOptions, polyOptions2;
Polyline polyline2;
List<LatLng> ltln;
private Double lat_decimal = 0.0,lng_decimal=0.0;
//initialize
ltln = new ArrayList<>();
//if you are using routing library
compile 'com.github.jd-alexander:library:1.0.7'
#Override
public void onRoutingSuccess(ArrayList<Route> arrayList, int i) {
//Add this code snippet on onRoutingSuccess to store latlan list
ltln = new ArrayList<>();
System.out.println("-----arrayList------" + arrayList.get(0).getPoints());
ltln = arrayList.get(0).getPoints();
// NOTE here already we draw polyLine 1
}
//below mentioned how to update polyline
private void UpdatePoliline(){
System.out.println("-------runnablePolyline-------"+ltln.size());
try {
if (ltln.size() > 0) {
for (int i = 0; i < ltln.size(); i++) {
ltln.remove(i);
if (CalculationByDistance(ltln.get(i), new LatLng(lat_decimal, lng_decimal)) >= 10) {
break;
}
}
polyOptions2 = new PolylineOptions();
polyOptions2.color(getResources().getColor(R.color.app_color));
polyOptions2.width(7);
polyOptions2.addAll(ltln);
if (polyline2 == null) {
polyline2 = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline2);
if (polyline != null) {
polyline.remove();
polyline = null;
}
} else {
polyline = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline);
if (polyline2 != null) {
polyline2.remove();
polyline2 = null;
}
}
System.out.println("=====waypoints new===" + ltln);
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
// Calculating distance between 2 points
public float CalculationByDistance(LatLng StartP, LatLng EndP) {
Location locationA = new Location("Source");
locationA.setLatitude(StartP.latitude);
locationA.setLongitude(StartP.longitude);
Location locationB = new Location("Destination");
locationB.setLatitude(EndP.latitude);
locationB.setLongitude(EndP.longitude);
float distance = locationA.distanceTo(locationB);
return distance;
}
//Redraw Polyline vehicle is not in current polyline with particular distance
if (ltln.size() > 0) {
if (PolyUtil.isLocationOnPath(new LatLng(currentlat, currentLon), ltln, false, 60.0f) ){
System.out.println("===tolarance===" + true);
} else {
//Redraw Polyline
}
}
UpdatePoliline();