Atul Dhanuka
Atul Dhanuka

Reputation: 1463

How can I place the customised marker in top of the Polygon in Google Maps

I want to place the customised bubble type marker on the top of the polygon with same text on it and when polygon is visible it should display and when polygon is gone then it should not display in map. How can I place the customised marker in top of the Polygon?

    coordinateList.add(new LatLng(19.216157, 72.920643));
    coordinateList.add(new LatLng(19.207537, 73.091977));
    coordinateList.add(new LatLng(19.012896, 73.012326));
    coordinateList.add(new LatLng(19.036265, 72.872251));

    PolygonOptions rectOptions = new PolygonOptions();
    rectOptions.addAll(coordinateList);
    rectOptions.strokeColor(Color.parseColor("#80FFFFFF"));
    rectOptions.strokeWidth(0);
    rectOptions.fillColor(Color.parseColor("#80ffb3ff"));
    polygon = mMap.addPolygon(rectOptions);
    polygon.setVisible(false);

Upvotes: 0

Views: 41

Answers (1)

antonio
antonio

Reputation: 18242

You can place your Marker on the centroid of the Polygon:

List<LatLng> coordinateList = new ArrayList<>();
Polygon polygon;
Marker marker;

coordinateList.add(new LatLng(19.216157, 72.920643));
coordinateList.add(new LatLng(19.207537, 73.091977));
coordinateList.add(new LatLng(19.012896, 73.012326));
coordinateList.add(new LatLng(19.036265, 72.872251));

PolygonOptions rectOptions = new PolygonOptions();
rectOptions.addAll(coordinateList);
rectOptions.strokeColor(Color.parseColor("#80FFFFFF"));
rectOptions.strokeWidth(0);
rectOptions.fillColor(Color.parseColor("#80ffb3ff"));
polygon = mMap.addPolygon(rectOptions);
polygon.setVisible(true);

LatLng centroid = findCentroid(coordinateList);

IconGenerator generator = new IconGenerator(this);
MarkerOptions markerOptions = new MarkerOptions().
        icon(BitmapDescriptorFactory.fromBitmap(generator.makeIcon("Title"))).
        position(centroid).
        anchor(generator.getAnchorU(), generator.getAnchorV());
marker = mMap.addMarker(markerOptions);

Here is the method to find the centroid

private LatLng findCentroid (List<LatLng> coordinates) {
    double latitude = 0;
    double longitude = 0;

    for (LatLng coordinate : coordinates) {
        latitude += coordinate.latitude;
        longitude += coordinate.longitude;
    }

    return new LatLng(latitude/coordinates.size(), longitude/coordinates.size());
}

Then you only need to make your Polygon and your Marker visible or invisible at the same time:

polygon.setVisible(false);
marker.setVisible(false);

Upvotes: 1

Related Questions