Make clickable polygons on Google Maps (for Android)

寵の児 提交于 2019-11-30 14:00:22
bittterbotter

Here's how I did it.

    Polygon polygon = getMap().addPolygon(new PolygonOptions()
                    .add(new LatLng(12.780712, 77.770956), new LatLng(12.912006, 77.229738), new LatLng(12.412006, 77.629738), new LatLng(12.912006, 77.229738))
                    .strokeColor(0xFF00AA00)
                    .fillColor(0x2200FFFF)
                    .strokeWidth(2)
    );


    polygon.setClickable(true);

    getMap().setOnPolygonClickListener(new GoogleMap.OnPolygonClickListener() {
        public void onPolygonClick(Polygon polygon) {

            mClusterManager = new ClusterManager<MyItem>(getApplicationContext(), getMap());
            getMap().setOnCameraChangeListener(mClusterManager);
            getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(getMap().getCameraPosition().target, getMap().getCameraPosition().zoom));

            try {
                readItems();
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(), "Problem reading list of markers.", Toast.LENGTH_LONG).show();
            }

        }
    });

Hope that helps.

you don't need to go crazy for having clickable polygon. I did it time ago but now, there is an api for that:

GoogleMap.setOnPolygonClickListener(OnPolygonClickListener)

You can use it easily:

GoogleMap mymap =....//init your map
mymap.setOnPolygonClickListener(new OnPolygonClickListener(){
 void onPolygonClick(Polygon polygon){
   //do whatever with polygon!
 }
});

In adding Polygon to the map. First create a PolygonOptions object and add some points to it. These points will form the outline of the polygon. You then add the polygon to the map by calling GoogleMap.addPolygon(PolygonOptions) which will return a Polygon object. This following code snippet show how to add polygon to a map.

// Instantiates a new Polygon object and adds points to define a rectangle PolygonOptions rectOptions = new PolygonOptions()
              .add(new LatLng(37.35, -122.0),
                   new LatLng(37.45, -122.0),
                   new LatLng(37.45, -122.2),
                   new LatLng(37.35, -122.2),
                   new LatLng(37.35, -122.0));

// Get back the mutable Polygon Polygon polygon = myMap.addPolygon(rectOptions);

By default, polygons are not clickable. You can enable and disable the clickability by calling Polygon.setClickable(boolean).

Like N Dorigatti said. In using OnPolygonClickListener to listen click events, call GoogleMap.setOnPolygonClickListener(OnPolygonClickListener).

When a user clicks on a polygon, you will receive an onPolygonClick(Polygon) callback. Check this document for more information.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!