I want to draw and remove Marker according to the previous conditions must be how
Example:
int a ;
if( a > 0 ) {
draw Marker
}
if(a == 0) {
remove Marker
}
You almost had it:
private Marker marker;
// ...
private void draw(int a) {
if (a == 0) {
if (marker != null) {
marker.remove();
marker = null;
}
} else if (a > 0) {
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(40,-4)));
}
}
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 have this code that is working exactly as I want. I mean I have a map fragment that displays 5 marker category, I can filter them as I want by category and everything works fine. As you might observe marker 1 and marker 8 will appear in more than one category. Here is the code and I will continue my problem afterwards:
Boolean mSetCameraPosition;
Boolean checkBox1Checked, checkBox2Checked, checkBox3Checked, checkBox4Checked, checkBox5Checked;
private int mapTypeSelected;
CheckBox cbAllDay, cbBefore12, cbBetween1216, cbBetween1620, ccbAfter20;
AlertDialog dialog;
List<Marker> firstCategoryList = new ArrayList<>();
List<Marker> secondCategoryList = new ArrayList<>();
List<Marker> thirdCategoryList = new ArrayList<>();
List<Marker> fourthCategoryList = new ArrayList<>();
List<Marker> fifthCategoryList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (savedInstanceState == null) {
mapTypeSelected = GoogleMap.MAP_TYPE_NORMAL;
mSetCameraPosition = true;
} else {
mapTypeSelected = savedInstanceState.getInt("the_map_type", GoogleMap.MAP_TYPE_NORMAL);
mSetCameraPosition = false;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (mSetCameraPosition) {
initialLocation(TOULOUSE_LAT, TOULOUSE_LNG, 12);
}
mMap.setMapType(mapTypeSelected);
if (initialMarkers) {
addMarkers2Map();
}
public void addMarkers2Map() {
// Markers location
LatLng marker1 = new LatLng(43.607044, 1.450307);
LatLng marker2= new LatLng(43.571505, 1.417759);
LatLng marker3= new LatLng(43.607469, 1.447162);
LatLng marker4= new LatLng(43.600723, 1.455917);
LatLng marker5= new LatLng(43.604892, 1.476562);
LatLng marker6= new LatLng(43.604496, 1.474924);
LatLng marker7= new LatLng(43.604781, 1.474502);
// Markers All day long
firstCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker1).title("First Place ").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 8.30 - 22.30")));
// Markers Before 12 PM
secondCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker2).title("Second Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 10.30 - 11.30")));
// Markers Between 12-16
thirdCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker3).title("Third Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 15.30 - 16.30")));
thirdCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker4).title("Fourth Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 15.00 - 16.00")));
// Markers Between 16-20
fourthCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker5).title("Fifth Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 15.30 - 16.30")));
fourthCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker6).title("Sixth Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 16.30 - 17.30")));
fourthCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker7).title("Seventh Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 18.30 - 19.30")));
fourthCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker8).title("Eighth Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 17.30 - 18.30\nHH:21.30 - 22.30")));
// Markers After 20
fifthCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker8).title("Eighth Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 17.30 - 18.30\nHH:21.30 - 22.30")));
fifthCategoryList.add(mMap.addMarker(new MarkerOptions().position(marker1).title("First Place").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 8.30 - 22.30")));
public void filterTheMarkers(View view) {
if (dialog == null){
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
#SuppressLint("InflateParams") View checkBoxView = inflater.inflate(R.layout.markers_filtering, null);
builder.setView(checkBoxView);
cbAllDay = (CheckBox) checkBoxView.findViewById(R.id.checkBox1);
if (checkBox1Checked != null) {
cbAllDay.setChecked(checkBox1Checked);
}
cbBefore12 = (CheckBox) checkBoxView.findViewById(R.id.checkBox2);
if (checkBox2Checked != null) {
cbBefore12.setChecked(checkBox2Checked);
}
cbBetween1216 = (CheckBox) checkBoxView.findViewById(R.id.checkBox3);
if (checkBox3Checked != null) {
cbBetween1216.setChecked(checkBox3Checked);
}
cbBetween1620 = (CheckBox) checkBoxView.findViewById(R.id.checkBox4);
if (checkBox4Checked != null) {
cbBetween1620.setChecked(checkBox4Checked);
}
ccbAfter20 = (CheckBox) checkBoxView.findViewById(R.id.checkBox5);
if (checkBox5Checked != null) {
ccbAfter20.setChecked(checkBox5Checked);
}
dialog = builder.create();
}
dialog.show();
}
public void displaySelectedMarkers(View view) {
dialog.dismiss();
Log.i("TAG", "All Day " + cbAllDay.isChecked() + " Before 12 " + cbBefore12.isChecked() + " Between 12-16 " + cbBetween1216.isChecked() + " Between 16-20" + cbBetween1620.isChecked() + " After 20 " + ccbAfter20.isChecked());
//according these check boxes status execute your code to show/hide markers
if (cbAllDay.isChecked() && cbBefore12.isChecked() && cbBetween1216.isChecked() && cbBetween1620.isChecked() && ccbAfter20.isChecked()) {
// show all markers
for (Marker marker : firstCategoryList) {
marker.setVisible(true);
}
for (Marker marker : secondCategoryList) {
marker.setVisible(true);
}
for (Marker marker : thirdCategoryList) {
marker.setVisible(true);
}
for (Marker marker : fourthCategoryList) {
marker.setVisible(true);
}
for (Marker marker : fifthCategoryList) {
marker.setVisible(true);
}
} else if (cbAllDay.isChecked() && !cbBefore12.isChecked() && !cbBetween1216.isChecked() && !cbBetween1620.isChecked() && !ccbAfter20.isChecked()) {
// show only All Day Markers
for (Marker marker : firstCategoryList) {
marker.setVisible(true);
}
for (Marker marker : secondCategoryList) {
marker.setVisible(false);
}
for (Marker marker : thirdCategoryList) {
marker.setVisible(false);
}
for (Marker marker : fourthCategoryList) {
marker.setVisible(false);
}
for (Marker marker : fifthCategoryList) {
marker.setVisible(false);
}
}
//....and it goes like this for a while until I finish all the possibilities
Now what I want to do is open a new activity for every markers info window clicked so the solution that I found is to add all the markers to a HashMap and give a name for every marker so that I can add it to the HashMap and to the ArrayList, like this:
private Map<Marker, Class> allMarkersMap = new HashMap<>();
Marker markerMarker1 = mMap.addMarker(new MarkerOptions().position(marker1).title("BAR ACASA").icon(BitmapDescriptorFactory.fromResource(R.drawable.beer_marker)).snippet("HH: 8.30 - 22.30"));
firstCategoryList.add(markerMarker1);
allMarkersMap.put(markerMarker1, Marker1.class);
Now on onMapReady I am adding this code and I create a class for every marker Marker1.java, Marker2.java.....:
mMap.setOnInfoWindowClickListener(MyOnInfoWindowClickListener);
GoogleMap.OnInfoWindowClickListener MyOnInfoWindowClickListener = new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Class cls = allMarkersMap.get(marker);
Intent intent = new Intent(MainActivity.this, cls );
startActivity(intent);
}
};
Everything works fine for the markers that appear only in one category, but for the ones that are in more than one category the filter is not working anymore, displaying only the markers that were last added to the HashMap(hopefully you understand what I am saying here).
So, can I do this and still have my filter functioning? As I am imagining that what is happening is the fact that once I define a marker and put it in the Arraylist it moves the marker there, and afterwards when I put it in the HashMap it moves it again to the HashMap so when I filter for arraylists the marker is not in the list anymore...
What would be the best solution for my info window opening a different activity for each marker displayed?
I won't write to much code for my solution because I think it would be better for you to write it and I think the idea behind it is more important than the code itself.
First of all, a small suggestion for you, whenever you start developing UI things that display information, try to find a generic description or a rule that describes the information that will be displayed. When you found that rule/description it means you found a model class.
I strongly suggest to use custom classes created by you that hold information required for your UI.
Now back to your example, from what I understand, you have markers that would be added to a category and based on that category you display them on the map.
What I would do I would create a custom class, called let's say MyAwesomeMarker that has a Marker member and a ArrayList<String> category.
Something like this:
public class MyAwesomeMarker {
private Marker mMarker;
private List<String> mMarkerCategories; // here you can mark if a marker is in more than one categories.
// constructors
public MyAwesomeMarker(Marker marker, String category) {
mMarker = marker;
mMarkerCategories = new ArrayList<String>();
mMarkerCategories.add(category);
}
public void addNewCategory(String category) {
if(category != null && !mMarkerCategorie.contains(category)) {
mMarkerCategories.add(category);
}
}
public void toggleMarkerIfHasCategory(String theCategory) {
for(String category : mMarkerCategories) {
if(category.equals(theCategory) {
marker.setVisible(true);
}
else {
marker.setVisible(false);
}
}
}
// setters getters
}
Then in your main class I would have a list of MyAwesomeMarker, let's call it myMarkers
Now you want to display all the markers that are in a category named awesomness.
for(MyAwesomeMarker marker : myMarkers) {
marker.toggleMarkerIfHasCategory("awesomness");
}
Now the only thing you have to do, is generate your lit of custom markers and you're done.
I am working on google map application,i want to find the area of irregular polygon with 4 markers,i have latitude and longitude of 4 points i want to find polygon area between points,please reply
code:
#Override
public void onMapClick(LatLng latLng) {
count++;
if (count <= 4) {
mMap.addMarker(new MarkerOptions().position(latLng).title(latLng.toString()));
markerClicked = false;
}
}
#Override
public boolean onMarkerClick(Marker marker) {
if (markerClicked) {
if (polygon != null) {
polygon.remove();
polygon = null;
}
polygonOptions.add(marker.getPosition());
polygonOptions.strokeColor(Color.parseColor("#cc0000"));
polygonOptions.fillColor(Color.parseColor("#332256"));
polygon = mMap.addPolygon(polygonOptions);
} else {
if (polygon != null) {
polygon.remove();
polygon = null;
}
polygonOptions = new PolygonOptions().add(marker.getPosition());
markerClicked = true;
}
return true;
}
Use Google Maps Android API Utility Library: computeArea.
You can use GeographicLib library , here documentation about computing polygon area by points.
I'm drawing polylines in google map v2 using marker drag, this is my code
int startDraw = 1;
Polyline polyline;
List<LatLng> lineCordinates = new ArrayList<LatLng>();
List<Polyline> polylines = new ArrayList<Polyline>();
#Override
public void onMarkerDrag(Marker marker) {
// startDraw == 0 --> stop draw
// startDraw == 1 --> start draw
if (startDraw == 1) {
Integer markerId = markerMapHash.get(marker);
if (markerId == null) {
markerId = 1;
}
if (markerId == 1) {
lineCordinates.add(marker.getPosition());
}
for (int i = 0; i < lineCordinates.size(); i++) {
polyline = myMap.addPolyline(new PolylineOptions()
.addAll(lineCordinates)
.width(lineWidth)
.color(lineColor));
polylines.add(polyline);
}
}
}
#Override
public void onMarkerDragEnd(Marker marker) {
lineCordinates.clear();
if (startDraw == 1) {
startDraw = 0;
}else{
startDraw = 1;
}
}
and to remove all polylines, this is the code in a button onClick
for(Polyline line : polylines){
line.remove();
}
polylines.clear();
Now I want to remove a specific polyline, how can I do this ?
Hope anyone could help me.
Thanks in advance.
I've never messed with this code before, but I assume you just need to check to see if line matches the specific polyline you're looking for and then remove it. Something like this:
for(Polyline line : polylines)
{
if (isSpecificPolyline(line))
line.remove();
}
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();