Hi i've the following code:
PolylineOptions myPolyline =new PolylineOptions();
go.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
...
myMap.addMarker(new MarkerOptions().position(start));
myPolyline.add(start);
myMap.addMarker(new MarkerOptions().position(destination));
myPolyline.add(destination);
fixZoom();
...
}
private void fixZoom() {
List<LatLng> points = myPolyline.getPoints();
LatLngBounds.Builder bc = new LatLngBounds.Builder();
for (LatLng item : points) {
bc.include(item);
}
myMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bc.build(), 50));}
If i've one of my markers OUT of my current screen, this code work fine but, when i've already all my markers in the current camera screen, zoom level wont change while I would like to see it changed to the minimum possible (zoom IN so).
I hope I made myself clear.
If you want to set zoom to a latlngbound, you have to set a zize to the map.
Look this example!
How to show multiple markers on MapFragment in Google Map API v2?
Related
I'm currently developing an android application that would allow users to draw Polylines with Markers on the map. Right now, I would like to implement a feature whereby the polyline will be draggable whenever the marker is being dragged and update the Polyline when the onMarkerDragEnd() method is being called. Does anyone know how I can achieve this? Below is a snippet of my codes. Thanks!
googleMap.setOnMapClickListener(new OnMapClickListener(){
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
if(drawMode == true && arrayPoints.isEmpty()){
MarkerOptions marker=new MarkerOptions();
marker.position(point);
googleMap.addMarker(marker).setDraggable(true);
arrayPoints.add(point);
marker.draggable(true);
}
else if(drawMode == true){
Log.e("","IN SECOND");
MarkerOptions marker=new MarkerOptions();
marker.position(point);
googleMap.addMarker(marker).setDraggable(true);
arrayPoints.add(point);
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLUE);
polylineOptions.width(5);
polylineOptions.addAll(arrayPoints);
Polyline drawRoute = googleMap.addPolyline(polylineOptions);
}
}
});
At first make Polyline drawRoute a field instead of a local variable.
Then you can update the polyline inside onMarkerDragEnd by calling drawRoute.setPoints(arrayPoints).
Then you need in addition a Java-Map, which keeps track of which marker was responsible for which point in the array. The map would have the marker-ID as key and the array-index as value. (You get the marker ID from the marker which is returned by map.addMarker)
When a marker is dragged, you can find out the index of the corresponding Point in arrayPoints using the marker-ID and said Java-Map. With that, you can exchange the point in the array and call drawRoute.setPoints again.
I haven't found any complete explanation on how to use this technique on Android so I decided to create a Q&A thread.
If your app has to show a large amount of markers on a google map and clustering them is not enough to prevent your app from working too slow, then one of your best choices is to use this Viewport Marker Management technique. You can read the theoretical explanation here: https://developers.google.com/maps/articles/toomanymarkers
I wrote a short guide below...
1°--- In the activity where map is created you have to set the OnCameraChangeListener and get the bounds of your screen like this:
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
LatLngBounds bounds = mapa.getProjection().getVisibleRegion().latLngBounds;
}
2°--- This step may vary depending how you fetch the markers data. Basically, what you have to do is to calculate if the lat and long of each of your markers are inside the screen bounds. I will show you how to do it by fetching the data from a SQLite data base storing latitud and longitude in two different DOUBLE clomuns inside the markers table.
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
LatLng northeast = bounds.northeast;
String boundLat = String.valueOf(northeast.latitude);
String boundLong = String.valueOf(northeast.longitude);
LatLng southwest = bounds.southwest;
String boundLat2 = String.valueOf(southwest.latitude);
String boundLong2 = String.valueOf(southwest.longitude);
//Remove all markers from map
mMap.clear(); // or if your a using cluster manager:
//mClusterManager.clearItems();
String[] fields = new String[] { "name", "latitude", "longitude" };
String[] args = new String[] {boundLat, boundLong, boundLat2, boundLong2,};
Cursor markers = dataBase.query("markers", fields, "latitude<=? AND longitude<=? AND latitude>=? AND longitude>=?");
if (markers.moveToFirst()) {
do {
mMap.addMarker(new MarkerOptions()
.position(new LatLng(marker.getDouble(1), marker.getDouble(2)))
.title(marker.getString(0)) );
// or if you are using cluster manager create and add the items as you normaly do.
} while (c.moveToNext());
//if using cluster manager add :
//mClusterManager.cluster();
}
}
});
The idea is pretty easy, just have in mind that your markers lat and longi have to be smaller than the northeast position of your screen and bigger than the southwest corner, or just use the LatLngBounds.contains function.
EDITED:
To avoid InfoWindow getting closed when clicking on a marker which is not already in the center of the screen, you can change the marker click listener default action, removing the camera move.
map.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
arg0.showInfoWindow();
return true; //must be true, if not, it will execute the default code after yours
}
});
I've been searching for help on implementing OnMarkerClickListener but nothing I've found has worked. This is my marker below and when clicked it only changes colour(light blue). I'm looking for it to open a bigger window so I can put in more info. Is this possible?
googlemap.addMarker(new MarkerOptions()
.position(new LatLng(49.378,-0.3904))
.title("Hello World")
.snippet("This is my test app")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
The marker works fine above on my Map but now I would like to click on the marker and for it to open a new activity/page or a bigger window, what ever is easier to work with. As I am a real novice at making apps, If anyone who has successfully got a working example please could you put up a link or some code.
Thanks in advance!
Edit:
From the tutorial that was suggested I have changed some of the MainActivity.java.
I've added in OnMarkerClickListener and have chosen to add unimplemented methods to the Public Class
public class MainActivity extends Activity implements LocationListener, OnMarkerClickListener {
Underneath private void setUpMap() I have added to my code: private Marker myMarker, the setonMarkerclick listener and myMarker =, :
private Marker myMarker;
{
googlemap.setOnMarkerClickListener(this);
myMarker = googlemap.addMarker(new MarkerOptions()
.position(new LatLng(LatLng))
.title("Hello World")
.snippet("My First App")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
}
In the unimplemented method at the bottom I have:
#Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub
return false;
What do I need to change in the public Boolean OnMarkerClick part?
I'm not getting any errors but its just not working. What else do I have to add in or change?
Any help is appreciated!
Marker click events
Don't snap to marker after click in android map v2
Quoting from the above post
You can use an OnMarkerClickListener to listen for click events on the marker. To set this listener on the map, call GoogleMap.setOnMarkerClickListener(OnMarkerClickListener). When a user clicks on a marker, onMarkerClick(Marker) will be called and the marker will be passed through as an argument. This method returns a boolean that indicates whether you have consumed the event (i.e., you want to suppress the default behavior). If it returns false, then the default behavior will occur in addition to your custom behavior. The default behavior for a marker click event is to show its info window (if available) and move the camera such that the marker is centered on the map.
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/GoogleMap.OnMarkerClickListener.
Use OnMarkerClickListener on your marker.
Check the link for code snippets
Google Maps API v2: How to make markers clickable?
Example: Works on my phone
Marker source, destination;
GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
source = mMap.addMarker(new MarkerOptions()
.position(sc)
.title("MyHome")
.snippet("Bangalore")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin)));
destination = mMap.addMarker(new MarkerOptions()
.position(lng)
.title("MapleBear Head Office")
.snippet("Jayanager")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin)));
mMap.setOnMarkerClickListener(marker -> {
if (marker.getTitle().equals("MyHome")) // if marker source is clicked
Toast.makeText(MainActivity.this, marker.getTitle(), Toast.LENGTH_SHORT).show();// display toast
return true;
});
This code handles the maker click event and loads a new layout (XML) with some information:
/**
* adding individual markers, displaying text on on marker click on a
* bubble, action of on marker bubble click
*/
private final void addLocationsToMap() {
int i = 0;
for (Stores store : storeList) {
LatLng l = new LatLng(store.getLatitude(), store.getLongtitude());
MarkerOptions marker = new MarkerOptions()
.position(l)
.title(store.getStoreName())
.snippet("" + i)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(marker);
++i;
}
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
try {
popUpWindow.setVisibility(View.VISIBLE);
Stores store = storeList.get(Integer.parseInt(marker
.getSnippet()));
// set details
email.setText(store.getEmail());
phoneNo.setText(store.getPhone());
address.setText(store.getAddress());
// setting test value to phone number
tempString = store.getPhone();
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0,
spanString.length(), 0);
phoneNo.setText(spanString);
// setting test value to email
tempStringemail = store.getEmail();
SpannableString spanString1 = new SpannableString(tempStringemail);
spanString1.setSpan(new UnderlineSpan(), 0, spanString1.length(), 0);
email.setText(spanString1);
storeLat = store.getLatitude();
storelng = store.getLongtitude();
} catch (ArrayIndexOutOfBoundsException e) {
Log.e("ArrayIndexOutOfBoundsException", " Occured");
}
}
});
}
If you need the event Click in a market,this code it's the solution.
private GoogleMap mGoogleMap;
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(Marker arg0) {
if(arg0 != null && arg0.getTitle().equals(markerOptions2.getTitle().toString())); // if marker source is clicked
Toast.makeText(menu.this, arg0.getTitle(), Toast.LENGTH_SHORT).show();// display toast
return true;
}
});
Good Luck
I suggest use of OnInfoWindowClickListener, it will trigger when you click on marker and then the snippet.
Use setTag to attach any object with the marker.
Marker marker = mMap.addMarker(markerOptions);
marker.setTag(myObject);
and the listener
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
MyObject mo = (MyObject )arg0.getTag();
}
});
Below code to used for Kotlin when user click on marker to perform any action
googleMap!!.setOnMarkerClickListener { marker ->
if (marker.title == "Marker1")
Log.d(TAG, "Clicked on Marker1")
true
}
I would like (in my Android app using Google maps api v2) to hide or show markers on my GoogleMap object according to a category, just like in the google maps web api, for example:
I have a GoogleMap with 50 Markers, 20 of them represent restaurants, 20 them represent bus stops, and 10 are cinemas.
Is it possible on Android google maps api v2 to do filtering on these markers, by hiding all the restaurant markers if we un-tick a checkbox for example?
I would like to do something like that but on my Android device using google maps api v2: http://www.geocodezip.com/v3_MW_example_categories.html
Sorry for the basic question but I am a beginner.
Try this way.
Marker restuarantMarkers = gMap.addMarker(new MarkerOptions()
.position(latlng)
.title("MyPlace").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin)).draggable(true));
On Click Event
restuarantMarkers.setVisible(false);
This way can do using loop..
Let me know if it works for you.
You can use dialog if you want to filter your locations.
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog);
Button bt_ok = (Button) dialog.findViewById(R.id.button1);
final CheckBox cb1 = (CheckBox) dialog.findViewById(R.id.checkBox1);
final CheckBox cb2 = (CheckBox) dialog.findViewById(R.id.checkBox2);
dialog.setTitle("Category");
bt_ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mMap.clear();
if (cb1.isChecked()){
mMap.addMarker(new MarkerOptions().position(new LatLng(44.109798, 15.242270)).title("Pin").icon(BitmapDescriptorFactory.fromResource(R.drawable.museum)));
}
if (cb2.isChecked()){
mMap.addMarker(new MarkerOptions().position(new LatLng(44.209798, 15.392270)).title("Pin 2").icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurants)));
}
dialog.dismiss();
}
});
dialog.show();
Yes you can! And here's how...
//mMap is an instance of GoogleMap that has already been initialized else where
mMap.setOnCameraChangeListener(getCameraChangeListener());
getCameraChangeListener()
public OnCameraChangeListener getCameraChangeListener()
{
return new OnCameraChangeListener()
{
#Override
public void onCameraChange(CameraPosition position)
{
addItemsToMap(this.items);
}
};
}
//Your "Item" class will need at least a unique id, latitude and longitude.
private void addItemsToMap(List<Item> items)
{
if(this.mMap != null)
{
LatLngBounds bounds = this.mMap.getProjection().getVisibleRegion().latLngBounds;
for(Item item : items)
{
if(bounds.contains(new LatLng(item.getLatitude(), item.getLongitude()))
{
if(!courseMarkers.containsKey(item.getId()))
{
this.courseMarkers.put(item.getId(), this.mMap.addMarker(getMarkerForItem(item)));
}
}
else
{
if(courseMarkers.containsKey(item.getId()))
{
courseMarkers.get(item.getId()).remove();
courseMarkers.remove(item.getId());
}
}
}
}
}
Here, LocationArray is ArrayList of Locations, which are plotted on map. We want to show all markers plotted on map.
private void FitAllMarkers() {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < LocationArray.size(); i++) {
builder.include(new LatLng(Double.parseDouble(LocationArray.get(i).getLat()), Double.parseDouble(LocationArray.get(i).getLng())));
}
LatLngBounds bounds = builder.build();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
}
Can anyone help me in the following task:
I want to add a marker in google map in android.
The functionality has to be like this that a pop up window have to be shown to add the touched location as a marker.
I was referring the below tutorial in that they add the marker through hard coding.
http://developer.android.com/resources/tutorials/views/hello-mapview.html
I want it that to be done using onclck on the map.
I used Google Maps API v2 and the solution is given below:
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(point.latitude, point.longitude))
.title("New Marker");
googleMap.addMarker(marker);
System.out.println(point.latitude + "---" + point.longitude);
}
});
In MapView you must use onTouch instead of onClick. The motionEvent that this event fires, has the touch coordinates so with the getProjection() method from MapView you can convert the touch coordinates into lat and long to put the Overlay (Marker) on the map.