Draw polygons on a map
Stay organized with collections
Save and categorize content based on your preferences.
Page Summary
-
This example demonstrates how to draw various polygons on a map using the Maps SDK for Android.
-
It showcases functionalities like creating polygons with holes, customizing fill and stroke colors, and handling click events.
-
Users can interact with SeekBars and Spinners to dynamically change the polygon's appearance, such as stroke width, joint type, and pattern.
-
The example code is provided in both Kotlin and Java, allowing developers to choose their preferred language.
-
To run the sample locally, users need to clone the repository, import the project into Android Studio, and configure their API key.
This example draws polygons of various shapes and colors on a map.
For more information, see the documentation.
Get started
Before you can try the sample code, you must configure your development environment. For more information, see Maps SDK for Android code samples.
View the code
Kotlin
overridefunonCreate(savedInstanceState:Bundle?){ super.onCreate(savedInstanceState) setContentView(R.layout.polygon_demo) fillHueBar=findViewById<SeekBar>(R.id.fillHueSeekBar).apply{ max=MAX_HUE_DEGREES progress=MAX_HUE_DEGREES/2 } fillAlphaBar=findViewById<SeekBar>(R.id.fillAlphaSeekBar).apply{ max=MAX_ALPHA progress=MAX_ALPHA/2 } strokeWidthBar=findViewById<SeekBar>(R.id.strokeWidthSeekBar).apply{ max=MAX_WIDTH_PX progress=MAX_WIDTH_PX/3 } strokeHueBar=findViewById<SeekBar>(R.id.strokeHueSeekBar).apply{ max=MAX_HUE_DEGREES progress=0 } strokeAlphaBar=findViewById<SeekBar>(R.id.strokeAlphaSeekBar).apply{ max=MAX_ALPHA progress=MAX_ALPHA } strokeJointTypeSpinner=findViewById<Spinner>(R.id.strokeJointTypeSpinner).apply{ adapter=ArrayAdapter( this@PolygonDemoActivity,android.R.layout.simple_spinner_item, getResourceStrings(jointTypeNameResourceIds)) } strokePatternSpinner=findViewById<Spinner>(R.id.strokePatternSpinner).apply{ adapter=ArrayAdapter( this@PolygonDemoActivity,android.R.layout.simple_spinner_item, getResourceStrings(patternTypeNameResourceIds)) } clickabilityCheckbox=findViewById(R.id.toggleClickability) valmapFragment=supportFragmentManager.findFragmentById(R.id.map)asSupportMapFragment mapFragment.getMapAsync(this) applyInsets(findViewById(R.id.map_container)) } overridefunonMapReady(googleMap:GoogleMap){ valfillColorArgb=Color.HSVToColor( fillAlphaBar.progress,floatArrayOf(fillHueBar.progress.toFloat(),1f,1f)) valstrokeColorArgb=Color.HSVToColor( strokeAlphaBar.progress,floatArrayOf(strokeHueBar.progress.toFloat(),1f,1f)) with(googleMap){ // Override the default content description on the view, for accessibility mode. setContentDescription(getString(R.string.polygon_demo_description)) // Move the googleMap so that it is centered on the mutable polygon. moveCamera(CameraUpdateFactory.newLatLngZoom(center,4f)) // Create a rectangle with two rectangular holes. mutablePolygon=addPolygon(PolygonOptions().apply{ addAll(createRectangle(center,5.0,5.0)) addHole(createRectangle(LatLng(-22.0,128.0),1.0,1.0)) addHole(createRectangle(LatLng(-18.0,133.0),0.5,1.5)) fillColor(fillColorArgb) strokeColor(strokeColorArgb) strokeWidth(strokeWidthBar.progress.toFloat()) clickable(clickabilityCheckbox.isChecked) }) // Add a listener for polygon clicks that changes the clicked polygon's stroke color. setOnPolygonClickListener{polygon-> // Flip the red, green and blue components of the polygon's stroke color. polygon.strokeColor=polygon.strokeColorxor0x00ffffff } } // set listeners on seekBars arrayOf(fillHueBar,fillAlphaBar,strokeWidthBar,strokeHueBar,strokeAlphaBar).map{ it.setOnSeekBarChangeListener(this) } // set listeners on spinners arrayOf(strokeJointTypeSpinner,strokePatternSpinner).map{ it.onItemSelectedListener=this } // set line pattern and joint type based on current spinner position with(mutablePolygon){ strokeJointType=getSelectedJointType(strokeJointTypeSpinner.selectedItemPosition) strokePattern=getSelectedPattern(strokePatternSpinner.selectedItemPosition) } }
Java
publicclass PolygonDemoActivityextendsSamplesBaseActivity implementsOnSeekBarChangeListener,OnItemSelectedListener,OnMapReadyCallback{ privatestaticfinalLatLngCENTER=newLatLng(-20,130); privatestaticfinalintMAX_WIDTH_PX=100; privatestaticfinalintMAX_HUE_DEGREES=360; privatestaticfinalintMAX_ALPHA=255; privatestaticfinalintPATTERN_DASH_LENGTH_PX=50; privatestaticfinalintPATTERN_GAP_LENGTH_PX=10; privatestaticfinalDotDOT=newDot(); privatestaticfinalDashDASH=newDash(PATTERN_DASH_LENGTH_PX); privatestaticfinalGapGAP=newGap(PATTERN_GAP_LENGTH_PX); privatestaticfinalList<PatternItem>PATTERN_DOTTED=Arrays.asList(DOT,GAP); privatestaticfinalList<PatternItem>PATTERN_DASHED=Arrays.asList(DASH,GAP); privatestaticfinalList<PatternItem>PATTERN_MIXED=Arrays.asList(DOT,GAP,DOT,DASH,GAP); privatePolygonmutablePolygon; privateSeekBarfillHueBar; privateSeekBarfillAlphaBar; privateSeekBarstrokeWidthBar; privateSeekBarstrokeHueBar; privateSeekBarstrokeAlphaBar; privateSpinnerstrokeJointTypeSpinner; privateSpinnerstrokePatternSpinner; privateCheckBoxclickabilityCheckbox; // These are the options for polygon stroke joints and patterns. We use their // string resource IDs as identifiers. privatestaticfinalint[]JOINT_TYPE_NAME_RESOURCE_IDS={ com.example.common_ui.R.string.joint_type_default,// Default com.example.common_ui.R.string.joint_type_bevel, com.example.common_ui.R.string.joint_type_round, }; privatestaticfinalint[]PATTERN_TYPE_NAME_RESOURCE_IDS={ com.example.common_ui.R.string.pattern_solid,// Default com.example.common_ui.R.string.pattern_dashed, com.example.common_ui.R.string.pattern_dotted, com.example.common_ui.R.string.pattern_mixed, }; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(com.example.common_ui.R.layout.polygon_demo); fillHueBar=findViewById(com.example.common_ui.R.id.fillHueSeekBar); fillHueBar.setMax(MAX_HUE_DEGREES); fillHueBar.setProgress(MAX_HUE_DEGREES/2); fillAlphaBar=findViewById(com.example.common_ui.R.id.fillAlphaSeekBar); fillAlphaBar.setMax(MAX_ALPHA); fillAlphaBar.setProgress(MAX_ALPHA/2); strokeWidthBar=findViewById(com.example.common_ui.R.id.strokeWidthSeekBar); strokeWidthBar.setMax(MAX_WIDTH_PX); strokeWidthBar.setProgress(MAX_WIDTH_PX/3); strokeHueBar=findViewById(com.example.common_ui.R.id.strokeHueSeekBar); strokeHueBar.setMax(MAX_HUE_DEGREES); strokeHueBar.setProgress(0); strokeAlphaBar=findViewById(com.example.common_ui.R.id.strokeAlphaSeekBar); strokeAlphaBar.setMax(MAX_ALPHA); strokeAlphaBar.setProgress(MAX_ALPHA); strokeJointTypeSpinner=findViewById(com.example.common_ui.R.id.strokeJointTypeSpinner); strokeJointTypeSpinner.setAdapter(newArrayAdapter<>( this,android.R.layout.simple_spinner_item, getResourceStrings(JOINT_TYPE_NAME_RESOURCE_IDS))); strokePatternSpinner=findViewById(com.example.common_ui.R.id.strokePatternSpinner); strokePatternSpinner.setAdapter(newArrayAdapter<>( this,android.R.layout.simple_spinner_item, getResourceStrings(PATTERN_TYPE_NAME_RESOURCE_IDS))); clickabilityCheckbox=findViewById(com.example.common_ui.R.id.toggleClickability); SupportMapFragmentmapFragment= (SupportMapFragment)getSupportFragmentManager().findFragmentById(com.example.common_ui.R.id.map); mapFragment.getMapAsync(this); applyInsets(findViewById(com.example.common_ui.R.id.map_container)); } @Override publicvoidonMapReady(GoogleMapmap){ // Override the default content description on the view, for accessibility mode. map.setContentDescription(getString(com.example.common_ui.R.string.polygon_demo_description)); intfillColorArgb=Color.HSVToColor( fillAlphaBar.getProgress(),newfloat[]{fillHueBar.getProgress(),1,1}); intstrokeColorArgb=Color.HSVToColor( strokeAlphaBar.getProgress(),newfloat[]{strokeHueBar.getProgress(),1,1}); // Create a rectangle with two rectangular holes. mutablePolygon=map.addPolygon(newPolygonOptions() .addAll(createRectangle(CENTER,5,5)) .addHole(createRectangle(newLatLng(-22,128),1,1)) .addHole(createRectangle(newLatLng(-18,133),0.5,1.5)) .fillColor(fillColorArgb) .strokeColor(strokeColorArgb) .strokeWidth(strokeWidthBar.getProgress()) .clickable(clickabilityCheckbox.isChecked())); fillHueBar.setOnSeekBarChangeListener(this); fillAlphaBar.setOnSeekBarChangeListener(this); strokeWidthBar.setOnSeekBarChangeListener(this); strokeHueBar.setOnSeekBarChangeListener(this); strokeAlphaBar.setOnSeekBarChangeListener(this); strokeJointTypeSpinner.setOnItemSelectedListener(this); strokePatternSpinner.setOnItemSelectedListener(this); mutablePolygon.setStrokeJointType(getSelectedJointType(strokeJointTypeSpinner.getSelectedItemPosition())); mutablePolygon.setStrokePattern(getSelectedPattern(strokePatternSpinner.getSelectedItemPosition())); // Move the map so that it is centered on the mutable polygon. map.moveCamera(CameraUpdateFactory.newLatLngZoom(CENTER,4)); // Add a listener for polygon clicks that changes the clicked polygon's stroke color. map.setOnPolygonClickListener(newGoogleMap.OnPolygonClickListener(){ @Override publicvoidonPolygonClick(Polygonpolygon){ // Flip the red, green and blue components of the polygon's stroke color. polygon.setStrokeColor(polygon.getStrokeColor()^0x00ffffff); } }); } }
Clone and run the samples
Git is required to run this sample locally. The following command clones the sample application repository.
git clone git@github.com:googlemaps-samples/android-samples.git
Import the sample project into Android Studio:
- In Android Studio, select File> New> Import Project.
Go to the location where you saved the repository and select the project directory for Kotlin or Java:
- Kotlin:
PATH-REPO/android-samples/ApiDemos/kotlin - Java:
PATH-REPO/android-samples/ApiDemos/java
- Kotlin:
- Select Open. Android Studio builds your project, using the Gradle build tool.
- Create a blank
secrets.propertiesfile in the same directory as your project'slocal.propertiesfile. For more information about this file, see Add your API key to the project. - Get an API key from your project with the Maps SDK for Android enabled.
Add the following string to
secrets.properties, replacing YOUR_API_KEY with the value of your API key:MAPS_API_KEY=YOUR_API_KEY- Run the app.