I want to draw polygon on google maps which may be resized. Any marker removed successfully by onMarkerClick but I can't change marker position by drag it to another place.
Here is my code:
PolygonOptions polygon = new PolygonOptions();
Polygon my_polygon ;
polygon.fillColor(Color.RED);
....
#Override
public boolean onMarkerClick(Marker arg0) {
my_polygon.remove();
arg0.remove();
polygon.getPoints().remove(arg0.getPosition()); //it's ok, marker deleted
return true;
}
#Override
public void onMarkerDrag(Marker marker)
{
polygon.getPoints().remove(marker.getPosition()); //marker still in polygon list
}
#Override
public void onMarkerDragStart(Marker marker)
{
polygon.getPoints().remove(marker.getPosition()); //marker still in polygon list
}
#Override
public void onMarkerDragEnd(Marker marker)
{
my_polygon.remove();
polygon.getPoints().remove(marker.getPosition()); //marker still in polygon list
polygon.add(marker.getPosition());
my_polygon=map.addPolygon(polygon); //created new polygon which contains previous marker position
}
So, how can I remove previus marker points correctly?
First keep all the LatLng points in a arraylist of LatLng.
Dont remove marker in
onMarkerDragStart(Marker marker) even save it to a new LatLng variable. Now at onMarkerDragEnd(Marker marker) , first get the new point and then remove the old one that u were save in the new LatLng variable . At the same time you need to remove the same marker from the arraylist that u have saved and add this new value and then draw a polygon again.
for example if suppose u have declare an arraylist of latlng like this
ArrayList points = new ArrayList();
then draw a ploygon in onMarkerDragEnd(Marker marker) like the following
Polygon polygon = map.addPolygon(new PolygonOptions()
.addAll(points)
.strokeColor(Color.BLACK)
.strokeWidth(5)
.fillColor(0x884d4d4d));
try this. hope it will help. :)
Related
I want to remove a Marker on long click, and place it in another place without clearing the whole map.
Right now the circle radius works fine, but the custom pin icon is not removed.
using the GoogleMap.clear() method should not be used - there are some other objects on the map I don't want refreshed.
I have also tried setPosition method and had the very same result.
How to erase this icon?
Marker declaration:
marker = googleMap.addMarker(new MarkerOptions().position(marker.getPosition()).draggable(true).title("INFO")
.infoWindowAnchor(0.5f,0.5f).visible(false)
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pin_icon))));
this.googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
if (marker != null) {
marker.remove();
}
createMarker(latLng);
}
});
private void createMarker(LatLng latLng) {
marker = googleMap.addMarker(new MarkerOptions().position(latLng).draggable(true).title("INFO")
.infoWindowAnchor(0.5f,0.5f)
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_pin_gr))));
}
I used such approach for creating markers and simply setPosition(new Latlng(...)) working.
marker = mGoogleMap.addMarker(new MarkerOptions()
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin))
.position(new LatLng(cab.getLatitude(), cab.getLongitude())));
Did you try to replace marker.remove(); on setPosition() inside onLongClick() method ?
Part of my application uses RecyclerView with CardView elements, and every CardView element contains Google Map which draws specific route. On every map I am zooming and positioning route inside of map so it can fill whole view but problems arrive when I begin to scroll and every next CardView doesn't position my route inside a map but leaves it unzoomed and unpositioned. Picture is below:
Im using onBindViewHolder to setup map and route drawing and then I'm using zoomToLatLng to zoom the map
#Override
public void onBindViewHolder(RouteViewHolder holder, int position) {
holder.destination.setText(routesCV.get(position).getDestination());
holder.startingPoint.setText(routesCV.get(position).getStartingPoint());
GoogleMap gMap = holder.map.getMap();
if (gMap != null) {
ArrayList<PointModel> mapPosition = routesCV.get(position).getPoints();
ArrayList<LatLng> points = new ArrayList<LatLng>();
for (PointModel item : mapPosition) {
points.add(new LatLng(item.getLatitude(),item.getLongitude()));
}
for (LatLng item : points) {
gMap.addMarker(new MarkerOptions().position(item));
}
zoomMapToLatLngBounds(holder.linearlayout, gMap, points);
}
}
Zoom method:
private void zoomMapToLatLngBounds(final LinearLayout layout,final GoogleMap mMap, final ArrayList<LatLng> bounds){
LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
for (int i=0; i<bounds.size(); i++) {
boundsBuilder.include(bounds.get(i));
}
final LatLngBounds boundsfinal = boundsBuilder.build();
final ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(boundsfinal, 25));
}
});
From logs public void onGlobalLayout() doesnt even execute. Do u know what might be the problem ? Tnx!
I made a OnMapLoadedCallback() function to position the map. It works now!
I am currently trying to add multiple markers to my Android application. This works just perfectly. The only thing I am getting stuck at is the fact that I cannot bind multiple "onInfoWindowClick" on multiple markers.
For instance, if I have like:
for (int i = 0; i < randomList; i++) {
MarkerOptions marker = new MarkerOptions().position(latlng).title(MainActivity.list.get(i).aMessage);
// adding marker
googleMap.addMarker(marker);
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// Do something onclick
}
});
}
This would result in a infowindowclick that works, for each marker, but I always get the same data back inside that "// Do something onclick", this is because the last marker is getting set to this event.
What is my procedure to attach this event to multiple markers?
Create a new Marker on every loop and execute the method: showInfoWindow();
for (int i = 0; i < randomList; i++) {
// MarkerOptions marker = new MarkerOptions().position(latlng).title(MainActivity.list.get(i).aMessage);
// adding marker
// googleMap.addMarker(marker);
googleMap.addMarker(new MarkerOptions().position(latlng).title(MainActivity.list.get(i).aMessage)).showInfoWindow();
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// Do something onclick
}
});
}
by the way you are setting the same latlng value!
You should not be calling setOnInfoWindowClickListener() inside a loop, this just needs to be called once, and it will apply to all Markers.
The Marker object that gets passed into onInfoWindowClick(Marker marker) will always be the Marker that was just clicked.
So, take that out of the loop. Next, in order to figure out what Marker was just clicked, you could get the title of the Marker, and loop through your list until you find the list item that has a aMessage value that corresponds to the Marker's title.
Note you could also identify that current marker by location by calling marker.getPosition();.
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
//get location of Marker that was just clicked
LatLng latLon = marker.getPosition();
// get the title of Marker that was just clicked
String title = marker.getTitle();
//find item in the list that corresponds to currently clicked Marker
for (int i = 0; i < MainActivity.this.list.size(); i++){
if (title.equals(MainActivity.this.list.get(i).aMessage)){
//found current list item corresponding to
//the Marker that was just clicked!
}
}
}
});
for (int i = 0; i < randomList; i++) {
MarkerOptions marker = new MarkerOptions().position(latlng).title(MainActivity.this.list.get(i).aMessage);
// adding marker
googleMap.addMarker(marker);
}
I answered a similar question here, you may find that helpful as well.
I want to make marker Application using Google Maps but . I Have problem about onMarkerClick using switch Case, Iam using array to add Marker to My Application and when marker OnCLick he can call different Activity for each marker .I Have problom about that.. How I can using onMarkerClick with switch case for my application..??? Please Help . Here is My Code :
public static final String TAG = markerbanyak.TAG;
final LatLng CENTER = new LatLng(43.661049, -79.400917);
class Data {
public Data(float lng, float lat, String title, String snippet, String icon) {
super();
this.lat = (float)lat;
this.lng = (float)lng;
this.title = title;
this.snippet = snippet;
this.icon = icon;
}
float lat;
float lng;
String title;
String snippet;
String icon;
}
Data[] data = {
new Data(-79.400917f,43.661049f, "New New College Res",
"Residence building (new concrete high-rise)", "R.drawable.mr_kun"),
new Data(-79.394524f,43.655796f, "Baldwin Street",
"Here be many good restaurants!", "R.drawable.mr_kun"),
new Data(-79.402206f,43.657688f, "College St",
"Lots of discount computer stores if you forgot a cable or need to buy hardware.", "R.drawable.mr_kun"),
new Data(-79.390381f,43.659878f, "Queens Park Subway",
"Quickest way to the north-south (Yonge-University-Spadina) subway/metro line", "R.drawable.mr_kun"),
new Data(-79.403732f,43.666801f, "Spadina Subway",
"Quickest way to the east-west (Bloor-Danforth) subway/metro line", "R.drawable.mr_kun"),
new Data(-79.399696f,43.667873f, "St George Subway back door",
"Token-only admittance, else use Spadina or Bedford entrances!", "R.drawable.mr_kun"),
new Data(-79.384163f,43.655083f, "Eaton Centre (megamall)",
"One of the largest indoor shopping centres in eastern Canada. Runs from Dundas to Queen.", "R.drawable.mr_kun"),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.peta);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
mMap = supportMapFragment.getMap();
Marker kuningan = mMap.addMarker(new MarkerOptions()
.position(KUNINGAN)
.title("Kuningan")
.snippet("Kuningan ASRI")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mr_kun)));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KUNINGAN, 2));
// Zoom in, animating the camera.
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
public void wisata(){
if (mMap==null) {
Log.d(TAG, "Map Fragment Not Found or no Map in it!!");
return;
}
for (Data d : data) {
LatLng location = new LatLng(d.lat, d.lng);
Marker wisata =mMap.addMarker(new MarkerOptions()
.position(location)
.title(d.title)
.snippet(d.snippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mr_wis)));
// Let the user see indoor maps where available.
mMap.setIndoorEnabled(true);
// Enable my-location stuff
mMap.setMyLocationEnabled(true);
// Move the "camera" (view position) to our center point.
mMap.moveCamera(CameraUpdateFactory.newLatLng(CENTER));
// Then animate the markers while the map is drawing,
// since you can't combine motion and zoom setting!
final int zoom = 14;
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom), 2000, null);
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker v) {
// TODO Auto-generated method stub
//(PLEASE HELP ME !!! :))
return false;
}
});
}
}
#Override
public boolean onMarkerClick(Marker v) {
// TODO Auto-generated method stub
//(PLEASE HELP ME !!! :))
if(v.getTitle().contains("New New College Res")){
// do if marker has this title
}else if(v.getTitle().contains("Baldwin Street")){
// do if marker has this title
} // and so on
return false;
}
});
Marker class if final so you can't extend it and add your own attributes. You will have to handle this using your own logic.
You can do this in two ways.
You already have a Data list with all marker data.
1) You could try to set "snippet" attribute of Marker with your array index of Data array and on onMarkerClick you can get Snippet change it back to int and that would be your Data Array's index. So you can get that your clicked Marker and it's Data object and do whatever you want to do.
2) Use HashMap.
It will look something like this
HashMap<Marker, Integer> hashMap = new HashMap<Marker, Integer>();
// now even in your loop where you are adding markers. you can also add that marker to this hashmap with the id of Data array's index.
hashMap.add(marker, indexOfDataArray);
// final in your onMarkerClick, you can just pass marker to hashMap and get indexOfDataArray and base of that do whatever you want to do.
int id = hashMap.get(marker);
Has anyone managed to use ItemizedOverlays in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available.
I've been trying to use the ItemizedOverlay and OverlayItem classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map.
I can add my own custom overlays using a similar technique, it's just the ItemizedOverlays that don't work.
Once I've implemented my own ItemizedOverlay (and overridden createItem), creating a new instance of my class seems to work (I can extract OverlayItems from it) but adding it to a map's Overlay list doesn't make it appear as it should.
This is the code I use to add the ItemizedOverlay class as an Overlay on to my MapView.
// Add the ItemizedOverlay to the Map
private void addItemizedOverlay() {
Resources r = getResources();
MapView mapView = (MapView)findViewById(R.id.mymapview);
List<Overlay> overlays = mapView.getOverlays();
MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon));
overlays.add(markers);
OverlayItem oi = markers.getItem(0);
markers.setFocus(oi);
mapView.postInvalidate();
}
Where MyItemizedOverlay is defined as:
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public MyItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
populate();
}
#Override
protected OverlayItem createItem(int index) {
Double lat = (index+37.422006)*1E6;
Double lng = -122.084095*1E6;
GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue());
OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text");
return oi;
}
#Override
public int size() {
return 5;
}
}
For the sake of completeness I'll repeat the discussion on Reto's post over at the Android Groups here.
It seems that if you set the bounds on your drawable it does the trick:
Drawable defaultMarker = r.getDrawable(R.drawable.icon);
// You HAVE to specify the bounds! It seems like the markers are drawn
// through Drawable.draw(Canvas) and therefore must have its bounds set
// before drawing.
defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),
defaultMarker.getIntrinsicHeight());
MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);
overlays.add(markers);
By the way, the above is shamelessly ripped from the demo at MarcelP.info. Also, here is a good howto.
try :
Drawable defaultMarker = r.getDrawable(R.drawable.icon);
defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),
defaultMarker.getIntrinsicHeight());
MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);
overlays.add(markers);