Draw polylines on a map

  • This guide demonstrates how to add and customize polylines on a map using the Maps SDK for Android, including setting color, width, and patterns.

  • The provided code samples showcase creating both geodesic and mutable polylines, along with event handling for clicks.

  • It is necessary to configure your development environment and clone the sample project repository from GitHub before running the code.

  • Instructions for importing and building the project in Android Studio, as well as for adding your API key are included.

This example adds and configures polylines on a map, such as to represent a directions route 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(com.example.common_ui.R.layout.polyline_demo)
hueBar=findViewById<SeekBar>(com.example.common_ui.R.id.hueSeekBar).apply{
max=MAX_HUE_DEGREES
progress=0
}
alphaBar=findViewById<SeekBar>(com.example.common_ui.R.id.alphaSeekBar).apply{
max=MAX_ALPHA
progress=MAX_ALPHA
}
widthBar=findViewById<SeekBar>(com.example.common_ui.R.id.widthSeekBar).apply{
max=MAX_WIDTH_PX
progress=MAX_WIDTH_PX/2
}
startCapSpinner=findViewById<Spinner>(com.example.common_ui.R.id.startCapSpinner).apply{
adapter=ArrayAdapter(this@PolylineDemoActivity,
android.R.layout.simple_spinner_item,
getResourceStrings(capTypeNameResourceIds))
}
endCapSpinner=findViewById<Spinner>(com.example.common_ui.R.id.endCapSpinner).apply{
adapter=ArrayAdapter(this@PolylineDemoActivity,
android.R.layout.simple_spinner_item,
getResourceStrings(capTypeNameResourceIds))
}
jointTypeSpinner=findViewById<Spinner>(com.example.common_ui.R.id.jointTypeSpinner).apply{
adapter=ArrayAdapter(this@PolylineDemoActivity,
android.R.layout.simple_spinner_item,
getResourceStrings(jointTypeNameResourceIds))
}
patternSpinner=findViewById<Spinner>(com.example.common_ui.R.id.patternSpinner).apply{
adapter=ArrayAdapter(
this@PolylineDemoActivity,android.R.layout.simple_spinner_item,
getResourceStrings(patternTypeNameResourceIds))
}
clickabilityCheckbox=findViewById<CheckBox>(com.example.common_ui.R.id.toggleClickability)
valmapFragment=supportFragmentManager.findFragmentById(com.example.common_ui.R.id.map)asSupportMapFragment
mapFragment.getMapAsync(this)
applyInsets(findViewById(com.example.common_ui.R.id.map_container))
}
overridefunonMapReady(googleMap:GoogleMap){
with(googleMap){
// Override the default content description on the view, for accessibility mode.
setContentDescription(getString(com.example.common_ui.R.string.polyline_demo_description))
// A geodesic polyline that goes around the world.
addPolyline(PolylineOptions().apply{
add(lhrLatLng,aklLatLng,laxLatLng,jfkLatLng,lhrLatLng)
width(INITIAL_STROKE_WIDTH_PX.toFloat())
color(Color.BLUE)
geodesic(true)
clickable(clickabilityCheckbox.isChecked)
})
// Move the googleMap so that it is centered on the mutable polyline.
moveCamera(CameraUpdateFactory.newLatLngZoom(melbourneLatLng,3f))
// Add a listener for polyline clicks that changes the clicked polyline's color.
setOnPolylineClickListener{polyline->
// Flip the values of the red, green and blue components of the polyline's color.
polyline.color=polyline.colorxor0x00ffffff
}
}
// A simple polyline across Australia. This polyline will be mutable.
mutablePolyline=googleMap.addPolyline(PolylineOptions().apply{
color(Color.HSVToColor(
alphaBar.progress,floatArrayOf(hueBar.progress.toFloat(),1f,1f)))
width(widthBar.progress.toFloat())
clickable(clickabilityCheckbox.isChecked)
add(melbourneLatLng,adelaideLatLng,perthLatLng,darwinLatLng)
})
arrayOf(hueBar,alphaBar,widthBar).map{
it.setOnSeekBarChangeListener(this)
}
arrayOf(startCapSpinner,endCapSpinner,jointTypeSpinner,patternSpinner).map{
it.onItemSelectedListener=this
}
with(mutablePolyline){
startCap=getSelectedCap(startCapSpinner.selectedItemPosition)?:ButtCap()
endCap=getSelectedCap(endCapSpinner.selectedItemPosition)?:ButtCap()
jointType=getSelectedJointType(jointTypeSpinner.selectedItemPosition)
pattern=getSelectedPattern(patternSpinner.selectedItemPosition)
}
clickabilityCheckbox.setOnClickListener{
view->mutablePolyline.isClickable=(viewasCheckBox).isChecked
}
}

Java

publicclass PolylineDemoActivityextendsSamplesBaseActivity
implementsOnSeekBarChangeListener,OnItemSelectedListener,OnMapReadyCallback{
// City locations for mutable polyline.
privatestaticfinalLatLngADELAIDE=newLatLng(-34.92873,138.59995);
privatestaticfinalLatLngDARWIN=newLatLng(-12.4258647,130.7932231);
privatestaticfinalLatLngMELBOURNE=newLatLng(-37.81319,144.96298);
privatestaticfinalLatLngPERTH=newLatLng(-31.95285,115.85734);
// Airport locations for geodesic polyline.
privatestaticfinalLatLngAKL=newLatLng(-37.006254,174.783018);
privatestaticfinalLatLngJFK=newLatLng(40.641051,-73.777485);
privatestaticfinalLatLngLAX=newLatLng(33.936524,-118.377686);
privatestaticfinalLatLngLHR=newLatLng(51.471547,-0.460052);
privatestaticfinalintMAX_WIDTH_PX=100;
privatestaticfinalintMAX_HUE_DEGREES=360;
privatestaticfinalintMAX_ALPHA=255;
privatestaticfinalintCUSTOM_CAP_IMAGE_REF_WIDTH_PX=50;
privatestaticfinalintINITIAL_STROKE_WIDTH_PX=5;
privatestaticfinalintPATTERN_DASH_LENGTH_PX=50;
privatestaticfinalintPATTERN_GAP_LENGTH_PX=20;
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);
privatePolylinemutablePolyline;
privateSeekBarhueBar;
privateSeekBaralphaBar;
privateSeekBarwidthBar;
privateSpinnerstartCapSpinner;
privateSpinnerendCapSpinner;
privateSpinnerjointTypeSpinner;
privateSpinnerpatternSpinner;
privateCheckBoxclickabilityCheckbox;
// These are the options for polyline caps, joints and patterns. We use their
// string resource IDs as identifiers.
privatestaticfinalint[]CAP_TYPE_NAME_RESOURCE_IDS={
com.example.common_ui.R.string.cap_butt,// Default
com.example.common_ui.R.string.cap_round,
com.example.common_ui.R.string.cap_square,
com.example.common_ui.R.string.cap_image,
};
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.polyline_demo);
hueBar=findViewById(com.example.common_ui.R.id.hueSeekBar);
hueBar.setMax(MAX_HUE_DEGREES);
hueBar.setProgress(0);
alphaBar=findViewById(com.example.common_ui.R.id.alphaSeekBar);
alphaBar.setMax(MAX_ALPHA);
alphaBar.setProgress(MAX_ALPHA);
widthBar=findViewById(com.example.common_ui.R.id.widthSeekBar);
widthBar.setMax(MAX_WIDTH_PX);
widthBar.setProgress(MAX_WIDTH_PX/2);
startCapSpinner=findViewById(com.example.common_ui.R.id.startCapSpinner);
startCapSpinner.setAdapter(newArrayAdapter<>(
this,android.R.layout.simple_spinner_item,
getResourceStrings(CAP_TYPE_NAME_RESOURCE_IDS)));
endCapSpinner=findViewById(com.example.common_ui.R.id.endCapSpinner);
endCapSpinner.setAdapter(newArrayAdapter<>(
this,android.R.layout.simple_spinner_item,
getResourceStrings(CAP_TYPE_NAME_RESOURCE_IDS)));
jointTypeSpinner=findViewById(com.example.common_ui.R.id.jointTypeSpinner);
jointTypeSpinner.setAdapter(newArrayAdapter<>(
this,android.R.layout.simple_spinner_item,
getResourceStrings(JOINT_TYPE_NAME_RESOURCE_IDS)));
patternSpinner=findViewById(com.example.common_ui.R.id.patternSpinner);
patternSpinner.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.polyline_demo_description));
// A geodesic polyline that goes around the world.
map.addPolyline(newPolylineOptions()
.add(LHR,AKL,LAX,JFK,LHR)
.width(INITIAL_STROKE_WIDTH_PX)
.color(Color.BLUE)
.geodesic(true)
.clickable(clickabilityCheckbox.isChecked()));
// A simple polyline across Australia. This polyline will be mutable.
intcolor=Color.HSVToColor(
alphaBar.getProgress(),newfloat[]{hueBar.getProgress(),1,1});
mutablePolyline=map.addPolyline(newPolylineOptions()
.color(color)
.width(widthBar.getProgress())
.clickable(clickabilityCheckbox.isChecked())
.add(MELBOURNE,ADELAIDE,PERTH,DARWIN));
hueBar.setOnSeekBarChangeListener(this);
alphaBar.setOnSeekBarChangeListener(this);
widthBar.setOnSeekBarChangeListener(this);
startCapSpinner.setOnItemSelectedListener(this);
endCapSpinner.setOnItemSelectedListener(this);
jointTypeSpinner.setOnItemSelectedListener(this);
patternSpinner.setOnItemSelectedListener(this);
mutablePolyline.setStartCap(getSelectedCap(startCapSpinner.getSelectedItemPosition()));
mutablePolyline.setEndCap(getSelectedCap(endCapSpinner.getSelectedItemPosition()));
mutablePolyline.setJointType(getSelectedJointType(jointTypeSpinner.getSelectedItemPosition()));
mutablePolyline.setPattern(getSelectedPattern(patternSpinner.getSelectedItemPosition()));
// Move the map so that it is centered on the mutable polyline.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(MELBOURNE,3));
// Add a listener for polyline clicks that changes the clicked polyline's color.
map.setOnPolylineClickListener(newGoogleMap.OnPolylineClickListener(){
@Override
publicvoidonPolylineClick(Polylinepolyline){
// Flip the values of the red, green and blue components of the polyline's color.
polyline.setColor(polyline.getColor()^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:

  1. In Android Studio, select File> New> Import Project.
  2. 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
  3. Select Open. Android Studio builds your project, using the Gradle build tool.
  4. Create a blank secrets.properties file in the same directory as your project's local.properties file. For more information about this file, see Add your API key to the project.
  5. Get an API key from your project with the Maps SDK for Android enabled.
  6. Add the following string to secrets.properties, replacing YOUR_API_KEY with the value of your API key:

    MAPS_API_KEY=YOUR_API_KEY
  7. Run the app.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026年09月01日 UTC.