Polylignes et polygones pour représenter des itinéraires et des zones

Ce tutoriel vous montre comment ajouter une carte Google à votre application Android, et comment utiliser des polylignes et des polygones pour représenter des itinéraires et des zones sur une carte.

Suivez ce tutoriel pour créer une application Android en utilisant le SDK Maps pour Android. L'environnement de développement recommandé est Android Studio.

Obtenir le code

Clonez ou téléchargez le dépôt d'exemples Google Maps Android API v2 à partir de GitHub.

Consultez la version Java de l'activité :

    // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.example.polygons;

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CustomCap;
import com.google.android.gms.maps.model.Dash;
import com.google.android.gms.maps.model.Dot;
import com.google.android.gms.maps.model.Gap;
import com.google.android.gms.maps.model.JointType;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PatternItem;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.maps.model.RoundCap;
import java.util.Arrays;
import java.util.List;

/**
 * An activity that displays a Google map with polylines to represent paths or routes,
 * and polygons to represent areas.
 */
public class PolyActivity extends AppCompatActivity
        implements
                OnMapReadyCallback,
                GoogleMap.OnPolylineClickListener,
                GoogleMap.OnPolygonClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera.
     * In this tutorial, we add polylines and polygons to represent routes and areas on the map.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {

        // Add polylines to the map.
        // Polylines are useful to show a route or some other connection between points.
        Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
                .clickable(true)
                .add(
                        new LatLng(-35.016, 143.321),
                        new LatLng(-34.747, 145.592),
                        new LatLng(-34.364, 147.891),
                        new LatLng(-33.501, 150.217),
                        new LatLng(-32.306, 149.248),
                        new LatLng(-32.491, 147.309)));
        // Store a data object with the polyline, used here to indicate an arbitrary type.
        polyline1.setTag("A");
        // Style the polyline.
        stylePolyline(polyline1);

        Polyline polyline2 = googleMap.addPolyline(new PolylineOptions()
                .clickable(true)
                .add(
                        new LatLng(-29.501, 119.700),
                        new LatLng(-27.456, 119.672),
                        new LatLng(-25.971, 124.187),
                        new LatLng(-28.081, 126.555),
                        new LatLng(-28.848, 124.229),
                        new LatLng(-28.215, 123.938)));
        polyline2.setTag("B");
        stylePolyline(polyline2);

        // Add polygons to indicate areas on the map.
        Polygon polygon1 = googleMap.addPolygon(new PolygonOptions()
                .clickable(true)
                .add(
                        new LatLng(-27.457, 153.040),
                        new LatLng(-33.852, 151.211),
                        new LatLng(-37.813, 144.962),
                        new LatLng(-34.928, 138.599)));
        // Store a data object with the polygon, used here to indicate an arbitrary type.
        polygon1.setTag("alpha");
        // Style the polygon.
        stylePolygon(polygon1);

        Polygon polygon2 = googleMap.addPolygon(new PolygonOptions()
                .clickable(true)
                .add(
                        new LatLng(-31.673, 128.892),
                        new LatLng(-31.952, 115.857),
                        new LatLng(-17.785, 122.258),
                        new LatLng(-12.4258, 130.7932)));
        polygon2.setTag("beta");
        stylePolygon(polygon2);

        // Position the map's camera near Alice Springs in the center of Australia,
        // and set the zoom factor so most of Australia shows on the screen.
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.684, 133.903), 4));

        // Set listeners for click events.
        googleMap.setOnPolylineClickListener(this);
        googleMap.setOnPolygonClickListener(this);
    }

    private static final int COLOR_BLACK_ARGB = 0xff000000;
    private static final int POLYLINE_STROKE_WIDTH_PX = 12;

    /**
     * Styles the polyline, based on type.
     * @param polyline The polyline object that needs styling.
     */
    private void stylePolyline(Polyline polyline) {
        String type = "";
        // Get the data object stored with the polyline.
        if (polyline.getTag() != null) {
            type = polyline.getTag().toString();
        }

        switch (type) {
            // If no type is given, allow the API to use the default.
            case "A":
                // Use a custom bitmap as the cap at the start of the line.
                polyline.setStartCap(
                        new CustomCap(
                                BitmapDescriptorFactory.fromResource(R.drawable.ic_arrow), 10));
                break;
            case "B":
                // Use a round cap at the start of the line.
                polyline.setStartCap(new RoundCap());
                break;
        }

        polyline.setEndCap(new RoundCap());
        polyline.setWidth(POLYLINE_STROKE_WIDTH_PX);
        polyline.setColor(COLOR_BLACK_ARGB);
        polyline.setJointType(JointType.ROUND);
    }

    private static final int PATTERN_GAP_LENGTH_PX = 20;
    private static final PatternItem DOT = new Dot();
    private static final PatternItem GAP = new Gap(PATTERN_GAP_LENGTH_PX);

    // Create a stroke pattern of a gap followed by a dot.
    private static final List<PatternItem> PATTERN_POLYLINE_DOTTED = Arrays.asList(GAP, DOT);

    /**
     * Listens for clicks on a polyline.
     * @param polyline The polyline object that the user has clicked.
     */
    @Override
    public void onPolylineClick(Polyline polyline) {
        // Flip from solid stroke to dotted stroke pattern.
        if ((polyline.getPattern() == null) || (!polyline.getPattern().contains(DOT))) {
            polyline.setPattern(PATTERN_POLYLINE_DOTTED);
        } else {
            // The default pattern is a solid stroke.
            polyline.setPattern(null);
        }

        Toast.makeText(this, "Route type " + polyline.getTag().toString(),
                Toast.LENGTH_SHORT).show();
    }

    /**
     * Listens for clicks on a polygon.
     * @param polygon The polygon object that the user has clicked.
     */
    @Override
    public void onPolygonClick(Polygon polygon) {
        // Flip the values of the red, green, and blue components of the polygon's color.
        int color = polygon.getStrokeColor() ^ 0x00ffffff;
        polygon.setStrokeColor(color);
        color = polygon.getFillColor() ^ 0x00ffffff;
        polygon.setFillColor(color);

        Toast.makeText(this, "Area type " + polygon.getTag().toString(), Toast.LENGTH_SHORT).show();
    }

    private static final int COLOR_WHITE_ARGB = 0xffffffff;
    private static final int COLOR_DARK_GREEN_ARGB = 0xff388E3C;
    private static final int COLOR_LIGHT_GREEN_ARGB = 0xff81C784;
    private static final int COLOR_DARK_ORANGE_ARGB = 0xffF57F17;
    private static final int COLOR_LIGHT_ORANGE_ARGB = 0xffF9A825;

    private static final int POLYGON_STROKE_WIDTH_PX = 8;
    private static final int PATTERN_DASH_LENGTH_PX = 20;
    private static final PatternItem DASH = new Dash(PATTERN_DASH_LENGTH_PX);

    // Create a stroke pattern of a gap followed by a dash.
    private static final List<PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(GAP, DASH);

    // Create a stroke pattern of a dot followed by a gap, a dash, and another gap.
    private static final List<PatternItem> PATTERN_POLYGON_BETA =
        Arrays.asList(DOT, GAP, DASH, GAP);

    /**
     * Styles the polygon, based on type.
     * @param polygon The polygon object that needs styling.
     */
    private void stylePolygon(Polygon polygon) {
        String type = "";
        // Get the data object stored with the polygon.
        if (polygon.getTag() != null) {
            type = polygon.getTag().toString();
        }

        List<PatternItem> pattern = null;
        int strokeColor = COLOR_BLACK_ARGB;
        int fillColor = COLOR_WHITE_ARGB;

        switch (type) {
            // If no type is given, allow the API to use the default.
            case "alpha":
                // Apply a stroke pattern to render a dashed line, and define colors.
                pattern = PATTERN_POLYGON_ALPHA;
                strokeColor = COLOR_DARK_GREEN_ARGB;
                fillColor = COLOR_LIGHT_GREEN_ARGB;
                break;
            case "beta":
                // Apply a stroke pattern to render a line of dots and dashes, and define colors.
                pattern = PATTERN_POLYGON_BETA;
                strokeColor = COLOR_DARK_ORANGE_ARGB;
                fillColor = COLOR_LIGHT_ORANGE_ARGB;
                break;
        }

        polygon.setStrokePattern(pattern);
        polygon.setStrokeWidth(POLYGON_STROKE_WIDTH_PX);
        polygon.setStrokeColor(strokeColor);
        polygon.setFillColor(fillColor);
    }
}

    

Consultez la version Kotlin de l'activité :

    // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.polygons

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnPolygonClickListener
import com.google.android.gms.maps.GoogleMap.OnPolylineClickListener
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.CustomCap
import com.google.android.gms.maps.model.Dash
import com.google.android.gms.maps.model.Dot
import com.google.android.gms.maps.model.Gap
import com.google.android.gms.maps.model.JointType
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.PatternItem
import com.google.android.gms.maps.model.Polygon
import com.google.android.gms.maps.model.PolygonOptions
import com.google.android.gms.maps.model.Polyline
import com.google.android.gms.maps.model.PolylineOptions
import com.google.android.gms.maps.model.RoundCap

/**
 * An activity that displays a Google map with polylines to represent paths or routes,
 * and polygons to represent areas.
 */
class PolyActivity : AppCompatActivity(), OnMapReadyCallback, OnPolylineClickListener, OnPolygonClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera.
     * In this tutorial, we add polylines and polygons to represent routes and areas on the map.
     */
    override fun onMapReady(googleMap: GoogleMap) {

        // Add polylines to the map.
        // Polylines are useful to show a route or some other connection between points.
        val polyline1 = googleMap.addPolyline(PolylineOptions()
            .clickable(true)
            .add(
                LatLng(-35.016, 143.321),
                LatLng(-34.747, 145.592),
                LatLng(-34.364, 147.891),
                LatLng(-33.501, 150.217),
                LatLng(-32.306, 149.248),
                LatLng(-32.491, 147.309)))
        // Store a data object with the polyline, used here to indicate an arbitrary type.
        polyline1.tag = "A"
        // Style the polyline.
        stylePolyline(polyline1)

        val polyline2 = googleMap.addPolyline(PolylineOptions()
            .clickable(true)
            .add(
                LatLng(-29.501, 119.700),
                LatLng(-27.456, 119.672),
                LatLng(-25.971, 124.187),
                LatLng(-28.081, 126.555),
                LatLng(-28.848, 124.229),
                LatLng(-28.215, 123.938)))
        polyline2.tag = "B"
        stylePolyline(polyline2)

        // Add polygons to indicate areas on the map.
        val polygon1 = googleMap.addPolygon(PolygonOptions()
            .clickable(true)
            .add(
                LatLng(-27.457, 153.040),
                LatLng(-33.852, 151.211),
                LatLng(-37.813, 144.962),
                LatLng(-34.928, 138.599)))
        // Store a data object with the polygon, used here to indicate an arbitrary type.
        polygon1.tag = "alpha"
        // Style the polygon.
        stylePolygon(polygon1)

        val polygon2 = googleMap.addPolygon(PolygonOptions()
            .clickable(true)
            .add(
                LatLng(-31.673, 128.892),
                LatLng(-31.952, 115.857),
                LatLng(-17.785, 122.258),
                LatLng(-12.4258, 130.7932)))
        polygon2.tag = "beta"
        stylePolygon(polygon2)

        // Position the map's camera near Alice Springs in the center of Australia,
        // and set the zoom factor so most of Australia shows on the screen.
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(-23.684, 133.903), 4f))

        // Set listeners for click events.
        googleMap.setOnPolylineClickListener(this)
        googleMap.setOnPolygonClickListener(this)
    }

    private val COLOR_BLACK_ARGB = -0x1000000
    private val POLYLINE_STROKE_WIDTH_PX = 12

    /**
     * Styles the polyline, based on type.
     * @param polyline The polyline object that needs styling.
     */
    private fun stylePolyline(polyline: Polyline) {
        // Get the data object stored with the polyline.
        val type = polyline.tag?.toString() ?: ""
        when (type) {
            "A" -> {
                // Use a custom bitmap as the cap at the start of the line.
                polyline.startCap = CustomCap(
                    BitmapDescriptorFactory.fromResource(R.drawable.ic_arrow), 10f)
            }
            "B" -> {
               // Use a round cap at the start of the line.
                polyline.startCap = RoundCap()
            }
        }
        polyline.endCap = RoundCap()
        polyline.width = POLYLINE_STROKE_WIDTH_PX.toFloat()
        polyline.color = COLOR_BLACK_ARGB
        polyline.jointType = JointType.ROUND
    }

    private val PATTERN_GAP_LENGTH_PX = 20
    private val DOT: PatternItem = Dot()
    private val GAP: PatternItem = Gap(PATTERN_GAP_LENGTH_PX.toFloat())

    // Create a stroke pattern of a gap followed by a dot.
    private val PATTERN_POLYLINE_DOTTED = listOf(GAP, DOT)

    /**
     * Listens for clicks on a polyline.
     * @param polyline The polyline object that the user has clicked.
     */
    override fun onPolylineClick(polyline: Polyline) {
        // Flip from solid stroke to dotted stroke pattern.
        if (polyline.pattern == null || !polyline.pattern!!.contains(DOT)) {
            polyline.pattern = PATTERN_POLYLINE_DOTTED
        } else {
            // The default pattern is a solid stroke.
            polyline.pattern = null
        }
        Toast.makeText(this, "Route type " + polyline.tag.toString(),
            Toast.LENGTH_SHORT).show()
    }

    /**
     * Listens for clicks on a polygon.
     * @param polygon The polygon object that the user has clicked.
     */
    override fun onPolygonClick(polygon: Polygon) {
        // Flip the values of the red, green, and blue components of the polygon's color.
        var color = polygon.strokeColor xor 0x00ffffff
        polygon.strokeColor = color
        color = polygon.fillColor xor 0x00ffffff
        polygon.fillColor = color
        Toast.makeText(this, "Area type ${polygon.tag?.toString()}", Toast.LENGTH_SHORT).show()
    }

    private val COLOR_WHITE_ARGB = -0x1
    private val COLOR_DARK_GREEN_ARGB = -0xc771c4
    private val COLOR_LIGHT_GREEN_ARGB = -0x7e387c
    private val COLOR_DARK_ORANGE_ARGB = -0xa80e9
    private val COLOR_LIGHT_ORANGE_ARGB = -0x657db
    private val POLYGON_STROKE_WIDTH_PX = 8
    private val PATTERN_DASH_LENGTH_PX = 20

    private val DASH: PatternItem = Dash(PATTERN_DASH_LENGTH_PX.toFloat())

    // Create a stroke pattern of a gap followed by a dash.
    private val PATTERN_POLYGON_ALPHA = listOf(GAP, DASH)

    // Create a stroke pattern of a dot followed by a gap, a dash, and another gap.
    private val PATTERN_POLYGON_BETA = listOf(DOT, GAP, DASH, GAP)

    /**
     * Styles the polygon, based on type.
     * @param polygon The polygon object that needs styling.
     */
    private fun stylePolygon(polygon: Polygon) {
        // Get the data object stored with the polygon.
        val type = polygon.tag?.toString() ?: ""
        var pattern: List<PatternItem>? = null
        var strokeColor = COLOR_BLACK_ARGB
        var fillColor = COLOR_WHITE_ARGB
        when (type) {
            "alpha" -> {
                // Apply a stroke pattern to render a dashed line, and define colors.
                pattern = PATTERN_POLYGON_ALPHA
                strokeColor = COLOR_DARK_GREEN_ARGB
                fillColor = COLOR_LIGHT_GREEN_ARGB
            }
            "beta" -> {
                // Apply a stroke pattern to render a line of dots and dashes, and define colors.
                pattern = PATTERN_POLYGON_BETA
                strokeColor = COLOR_DARK_ORANGE_ARGB
                fillColor = COLOR_LIGHT_ORANGE_ARGB
            }
        }
        polygon.strokePattern = pattern
        polygon.strokeWidth = POLYGON_STROKE_WIDTH_PX.toFloat()
        polygon.strokeColor = strokeColor
        polygon.fillColor = fillColor
    }
}

    

Configurer votre projet de développement

Suivez les étapes ci-dessous pour créer le projet du tutoriel dans Android Studio.

  1. Téléchargez et installez Android Studio.
  2. Ajoutez le package de services Google Play à Android Studio.
  3. Clonez ou téléchargez le dépôt d'exemples Google Maps Android API v2 si vous ne l'avez pas déjà fait au début de ce tutoriel.
  4. Importez le projet du tutoriel :

    • Dans Android Studio, sélectionnez File > New > Import Project (Fichier > Nouveau > Importer un projet).
    • Accédez à l'emplacement où vous avez enregistré le référentiel d'exemples Google Maps Android API v2 après l'avoir téléchargé.
    • Localisez le projet Polygons à l'emplacement suivant :
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/Polygons (Java) ou
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/Polygons (Kotlin)
    • Sélectionnez le répertoire du projet, puis cliquez sur Open (Ouvrir). Android Studio crée à présent votre projet à l'aide de l'outil de compilation Gradle.

Activer les API nécessaires et obtenir une clé API

Pour suivre ce tutoriel, vous devez disposer d'un projet Google Cloud avec les API nécessaires activées et d'une clé API autorisée à utiliser le SDK Maps pour Android. Pour en savoir plus, consultez les pages suivantes :

Ajouter la clé API à votre application

  1. Ouvrez le fichier local.properties de votre projet.
  2. Ajoutez la chaîne suivante, puis remplacez YOUR_API_KEY par la valeur de votre clé API :

    MAPS_API_KEY=YOUR_API_KEY
    

    Lorsque vous compilez l'application, le plug-in Secrets Gradle pour Android copie la clé API et la met à disposition en tant que variable de compilation dans le fichier manifeste Android, comme expliqué ci-dessous.

Compiler et exécuter votre application

Pour compiler et exécuter l'application :

  1. Connectez un appareil Android à votre ordinateur. Suivez les instructions pour activer les options pour les développeurs sur votre appareil Android et configurer votre système afin qu'il détecte l'appareil.

    Vous pouvez également utiliser l'outil AVD (Android Virtual Device) Manager pour configurer un appareil virtuel. Lorsque vous choisissez un émulateur, assurez-vous de sélectionner une image qui inclut les APIs Google. Pour en savoir plus, consultez Configurer un projet Android Studio.

  2. Dans Android Studio, cliquez sur l'option de menu Run (Exécuter) ou sur l'icône du bouton de lecture. Choisissez un appareil lorsque vous y êtes invité.

Android Studio invoque Gradle pour créer l'application, puis l'exécute sur l'appareil ou sur l'émulateur.

Vous devriez voir une carte avec deux polygones superposés en haut de l'Australie, comme dans l'image sur cette page.

Résolution des erreurs :

  • Si aucune carte ne s'affiche, vérifiez que vous avez bien obtenu une clé API et que vous l'avez ajoutée à l'application, comme décrit ci-dessus. Consultez le journal Android Monitor d'Android Studio pour vérifier s'il contient des messages d'erreur concernant la clé API.
  • Utilisez les outils de débogage d'Android Studio pour afficher les journaux et déboguer l'application.

Comprendre le code

Cette partie du tutoriel décrit les principales composantes de l'application Polygons pour vous aider à comprendre comment créer une application similaire.

Vérifier votre fichier manifeste Android

Notez les éléments suivants dans le fichier AndroidManifest.xml de votre application :

  • Ajoutez un élément meta-data pour intégrer la version des services Google Play avec laquelle l'application a été compilée.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • Ajoutez un élément meta-data spécifiant votre clé API. L'échantillon fourni avec ce tutoriel mappe la valeur de la clé d'API sur une variable de compilation correspondant au nom de la clé que vous avez définie précédemment, MAPS_API_KEY. Lorsque vous compilez l'application, le plug-in Secrets Gradle pour Android met les clés de votre fichier local.properties à disposition en tant que variables de compilation de fichier manifeste.

    <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="${MAPS_API_KEY}" />
    

    Dans votre fichier build.gradle, la ligne suivante transmet votre clé API à votre fichier manifeste Android.

      id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    

Voici un exemple complet de fichier manifeste :

  <?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright 2020 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.polygons">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
             The API key for Google Maps-based APIs.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="${MAPS_API_KEY}" />

        <activity
            android:name="com.example.polygons.PolyActivity"
            android:exported="true"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

  

Ajouter une carte

Affichez une carte à l'aide du SDK Maps pour Android.

  1. Ajoutez un élément <fragment> au fichier de mise en page de votre activité (activity_maps.xml). Cet élément définit un fragment SupportMapFragment pour servir de conteneur à la carte et donner accès à l'objet GoogleMap. Ce tutoriel utilise la version du fragment de carte issue de la bibliothèque Android Support afin de garantir sa rétrocompatibilité avec les versions précédentes du framework Android.

    <!--
     Copyright 2020 Google LLC
    
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
    -->
    
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.polygons.PolyActivity" />
    
    
  2. Dans la méthode onCreate() de votre activité, définissez le fichier de mise en page en tant que vue de contenu. Obtenez un handle vers le fragment de carte en appelant FragmentManager.findFragmentById(). Ensuite, utilisez getMapAsync() pour vous inscrire au rappel de la carte :

    Java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    

    Kotlin

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)
    }
    
  3. Ajoutez l'interface OnMapReadyCallback et ignorez la méthode onMapReady(). L'API invoque ce rappel lorsque l'objet GoogleMap est disponible. Vous pouvez ainsi ajouter des objets à la carte et la personnaliser pour votre application :

    Java

    public class PolyActivity extends AppCompatActivity
            implements
                    OnMapReadyCallback,
                    GoogleMap.OnPolylineClickListener,
                    GoogleMap.OnPolygonClickListener {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Retrieve the content view that renders the map.
            setContentView(R.layout.activity_maps);
    
            // Get the SupportMapFragment and request notification when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }
    
        /**
         * Manipulates the map when it's available.
         * The API invokes this callback when the map is ready to be used.
         * This is where we can add markers or lines, add listeners or move the camera.
         * In this tutorial, we add polylines and polygons to represent routes and areas on the map.
         */
        @Override
        public void onMapReady(GoogleMap googleMap) {
    
            // Add polylines to the map.
            // Polylines are useful to show a route or some other connection between points.
            Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
                    .clickable(true)
                    .add(
                            new LatLng(-35.016, 143.321),
                            new LatLng(-34.747, 145.592),
                            new LatLng(-34.364, 147.891),
                            new LatLng(-33.501, 150.217),
                            new LatLng(-32.306, 149.248),
                            new LatLng(-32.491, 147.309)));
    
            // Position the map's camera near Alice Springs in the center of Australia,
            // and set the zoom factor so most of Australia shows on the screen.
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.684, 133.903), 4));
    
            // Set listeners for click events.
            googleMap.setOnPolylineClickListener(this);
            googleMap.setOnPolygonClickListener(this);
        }
    

    Kotlin

    class PolyActivity : AppCompatActivity(), OnMapReadyCallback, OnPolylineClickListener, OnPolygonClickListener {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            // Retrieve the content view that renders the map.
            setContentView(R.layout.activity_maps)
    
            // Get the SupportMapFragment and request notification when the map is ready to be used.
            val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment?
            mapFragment?.getMapAsync(this)
        }
    
        /**
         * Manipulates the map when it's available.
         * The API invokes this callback when the map is ready to be used.
         * This is where we can add markers or lines, add listeners or move the camera.
         * In this tutorial, we add polylines and polygons to represent routes and areas on the map.
         */
        override fun onMapReady(googleMap: GoogleMap) {
    
            // Add polylines to the map.
            // Polylines are useful to show a route or some other connection between points.
            val polyline1 = googleMap.addPolyline(PolylineOptions()
                .clickable(true)
                .add(
                    LatLng(-35.016, 143.321),
                    LatLng(-34.747, 145.592),
                    LatLng(-34.364, 147.891),
                    LatLng(-33.501, 150.217),
                    LatLng(-32.306, 149.248),
                    LatLng(-32.491, 147.309)))
    
            // Position the map's camera near Alice Springs in the center of Australia,
            // and set the zoom factor so most of Australia shows on the screen.
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(-23.684, 133.903), 4f))
    
            // Set listeners for click events.
            googleMap.setOnPolylineClickListener(this)
            googleMap.setOnPolygonClickListener(this)
        }
    

Ajouter une polyligne pour tracer une ligne sur la carte

Une Polyline est une série de segments de ligne connectés. Les polylignes sont utiles pour représenter des itinéraires, des trajets ou d'autres connexions entre des lieux sur la carte.

  1. Créez un objet PolylineOptions et ajoutez-lui des points. Chaque point représente un emplacement sur la carte, que vous définissez avec un objet LatLng contenant des valeurs de latitude et de longitude. L'exemple de code ci-dessous crée une polyligne comportant six points.

  2. Appelez GoogleMap.addPolyline() pour ajouter la polyligne à la carte.

    Java

    Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
            .clickable(true)
            .add(
                    new LatLng(-35.016, 143.321),
                    new LatLng(-34.747, 145.592),
                    new LatLng(-34.364, 147.891),
                    new LatLng(-33.501, 150.217),
                    new LatLng(-32.306, 149.248),
                    new LatLng(-32.491, 147.309)));
    

    Kotlin

    val polyline1 = googleMap.addPolyline(PolylineOptions()
        .clickable(true)
        .add(
            LatLng(-35.016, 143.321),
            LatLng(-34.747, 145.592),
            LatLng(-34.364, 147.891),
            LatLng(-33.501, 150.217),
            LatLng(-32.306, 149.248),
            LatLng(-32.491, 147.309)))
    

Définissez l'option clickable de la polyligne sur true si vous souhaitez gérer les événements de clic sur la polyligne. Vous trouverez plus d'informations sur la gestion des événements dans ce tutoriel.

Stocker des données arbitraires avec une polyligne

Vous pouvez stocker des objets de données arbitraires avec des polylignes et d'autres objets de géométrie.

  1. Appelez Polyline.setTag() pour stocker un objet de données avec la polyligne. Le code ci-dessous définit un tag arbitraire (A) indiquant un type de polyligne.

    Java

    Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
        .clickable(true)
        .add(
                new LatLng(-35.016, 143.321),
                new LatLng(-34.747, 145.592),
                new LatLng(-34.364, 147.891),
                new LatLng(-33.501, 150.217),
                new LatLng(-32.306, 149.248),
                new LatLng(-32.491, 147.309)));
    // Store a data object with the polyline, used here to indicate an arbitrary type.
    polyline1.setTag("A");
    

    Kotlin

    val polyline1 = googleMap.addPolyline(PolylineOptions()
    .clickable(true)
    .add(
        LatLng(-35.016, 143.321),
        LatLng(-34.747, 145.592),
        LatLng(-34.364, 147.891),
        LatLng(-33.501, 150.217),
        LatLng(-32.306, 149.248),
        LatLng(-32.491, 147.309)))
    // Store a data object with the polyline, used here to indicate an arbitrary type.
    polyline1.tag = "A
    
  2. Récupérez les données en utilisant Polyline.getTag(), comme le montre la section suivante.

Ajouter un style personnalisé à votre polyligne

Vous pouvez spécifier différentes propriétés de style dans l'objet PolylineOptions. Les options de style incluent la couleur du trait, la largeur du trait, la forme du trait, les types de jointure, ainsi que les terminaisons de début et de fin. Si vous ne spécifiez pas de propriété particulière, l'API utilise la valeur par défaut de cette propriété.

Le code suivant applique une terminaison arrondie à la fin de la ligne et une terminaison de début qui varie selon le type de la polyligne, le type étant une propriété arbitraire stockée dans l'objet de données de la polyligne. L'exemple spécifie également une largeur de trait, une couleur de trait et un type de jointure :

Java

private static final int COLOR_BLACK_ARGB = 0xff000000;
private static final int POLYLINE_STROKE_WIDTH_PX = 12;

/**
 * Styles the polyline, based on type.
 * @param polyline The polyline object that needs styling.
 */
private void stylePolyline(Polyline polyline) {
    String type = "";
    // Get the data object stored with the polyline.
    if (polyline.getTag() != null) {
        type = polyline.getTag().toString();
    }

    switch (type) {
        // If no type is given, allow the API to use the default.
        case "A":
            // Use a custom bitmap as the cap at the start of the line.
            polyline.setStartCap(
                    new CustomCap(
                            BitmapDescriptorFactory.fromResource(R.drawable.ic_arrow), 10));
            break;
        case "B":
            // Use a round cap at the start of the line.
            polyline.setStartCap(new RoundCap());
            break;
    }

    polyline.setEndCap(new RoundCap());
    polyline.setWidth(POLYLINE_STROKE_WIDTH_PX);
    polyline.setColor(COLOR_BLACK_ARGB);
    polyline.setJointType(JointType.ROUND);
}

Kotlin

private val COLOR_BLACK_ARGB = -0x1000000
private val POLYLINE_STROKE_WIDTH_PX = 12

/**
 * Styles the polyline, based on type.
 * @param polyline The polyline object that needs styling.
 */
private fun stylePolyline(polyline: Polyline) {
    // Get the data object stored with the polyline.
    val type = polyline.tag?.toString() ?: ""
    when (type) {
        "A" -> {
            // Use a custom bitmap as the cap at the start of the line.
            polyline.startCap = CustomCap(
                BitmapDescriptorFactory.fromResource(R.drawable.ic_arrow), 10f)
        }
        "B" -> {
           // Use a round cap at the start of the line.
            polyline.startCap = RoundCap()
        }
    }
    polyline.endCap = RoundCap()
    polyline.width = POLYLINE_STROKE_WIDTH_PX.toFloat()
    polyline.color = COLOR_BLACK_ARGB
    polyline.jointType = JointType.ROUND
}

Le code ci-dessus spécifie une image bitmap personnalisée pour le début de la polyligne de type A et spécifie une largeur de trait de référence de 10 pixels. L'API met à l'échelle l'image bitmap en fonction de la largeur du trait de référence. Lorsque vous spécifiez la largeur du trait de référence, indiquez la largeur que vous avez utilisée lors de la conception de l'image bitmap, à la dimension d'origine de l'image. Conseil : ouvrez l'image bitmap à 100 % de zoom dans un éditeur d'images et définissez la largeur de trait souhaitée par rapport à l'image.

En savoir plus sur les extrémités de ligne et les autres options de personnalisation des formes

Gérer les événements de clic sur la polyligne

  1. Rendez la polyligne cliquable en appelant la méthode Polyline.setClickable(). Par défaut, les polylignes ne sont pas cliquables, et votre application ne reçoit pas de notification lorsque l'utilisateur appuie sur une polyligne.

  2. Ajoutez l'interface OnPolylineClickListener et appelez la méthode GoogleMap.setOnPolylineClickListener() pour définir l'écouteur sur la carte :

    Java

    public class PolyActivity extends AppCompatActivity
            implements
                    OnMapReadyCallback,
                    GoogleMap.OnPolylineClickListener,
                    GoogleMap.OnPolygonClickListener {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Retrieve the content view that renders the map.
            setContentView(R.layout.activity_maps);
    
            // Get the SupportMapFragment and request notification when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }
    
        /**
         * Manipulates the map when it's available.
         * The API invokes this callback when the map is ready to be used.
         * This is where we can add markers or lines, add listeners or move the camera.
         * In this tutorial, we add polylines and polygons to represent routes and areas on the map.
         */
        @Override
        public void onMapReady(GoogleMap googleMap) {
    
            // Add polylines to the map.
            // Polylines are useful to show a route or some other connection between points.
            Polyline polyline1 = googleMap.addPolyline(new PolylineOptions()
                    .clickable(true)
                    .add(
                            new LatLng(-35.016, 143.321),
                            new LatLng(-34.747, 145.592),
                            new LatLng(-34.364, 147.891),
                            new LatLng(-33.501, 150.217),
                            new LatLng(-32.306, 149.248),
                            new LatLng(-32.491, 147.309)));
    
            // Position the map's camera near Alice Springs in the center of Australia,
            // and set the zoom factor so most of Australia shows on the screen.
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.684, 133.903), 4));
    
            // Set listeners for click events.
            googleMap.setOnPolylineClickListener(this);
            googleMap.setOnPolygonClickListener(this);
        }
    

    Kotlin

    class PolyActivity : AppCompatActivity(), OnMapReadyCallback, OnPolylineClickListener, OnPolygonClickListener {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            // Retrieve the content view that renders the map.
            setContentView(R.layout.activity_maps)
    
            // Get the SupportMapFragment and request notification when the map is ready to be used.
            val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment?
            mapFragment?.getMapAsync(this)
        }
    
        /**
         * Manipulates the map when it's available.
         * The API invokes this callback when the map is ready to be used.
         * This is where we can add markers or lines, add listeners or move the camera.
         * In this tutorial, we add polylines and polygons to represent routes and areas on the map.
         */
        override fun onMapReady(googleMap: GoogleMap) {
    
            // Add polylines to the map.
            // Polylines are useful to show a route or some other connection between points.
            val polyline1 = googleMap.addPolyline(PolylineOptions()
                .clickable(true)
                .add(
                    LatLng(-35.016, 143.321),
                    LatLng(-34.747, 145.592),
                    LatLng(-34.364, 147.891),
                    LatLng(-33.501, 150.217),
                    LatLng(-32.306, 149.248),
                    LatLng(-32.491, 147.309)))
    
            // Position the map's camera near Alice Springs in the center of Australia,
            // and set the zoom factor so most of Australia shows on the screen.
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(-23.684, 133.903), 4f))
    
            // Set listeners for click events.
            googleMap.setOnPolylineClickListener(this)
            googleMap.setOnPolygonClickListener(this)
        }
    
  3. Ignorez la méthode de rappel onPolylineClick(). L'exemple suivant modifie le motif du trait en passant de la ligne continue à la ligne en pointillé chaque fois que l'utilisateur clique sur la polyligne :

    Java

    private static final int PATTERN_GAP_LENGTH_PX = 20;
    private static final PatternItem DOT = new Dot();
    private static final PatternItem GAP = new Gap(PATTERN_GAP_LENGTH_PX);
    
    // Create a stroke pattern of a gap followed by a dot.
    private static final List<PatternItem> PATTERN_POLYLINE_DOTTED = Arrays.asList(GAP, DOT);
    
    /**
     * Listens for clicks on a polyline.
     * @param polyline The polyline object that the user has clicked.
     */
    @Override
    public void onPolylineClick(Polyline polyline) {
        // Flip from solid stroke to dotted stroke pattern.
        if ((polyline.getPattern() == null) || (!polyline.getPattern().contains(DOT))) {
            polyline.setPattern(PATTERN_POLYLINE_DOTTED);
        } else {
            // The default pattern is a solid stroke.
            polyline.setPattern(null);
        }
    
        Toast.makeText(this, "Route type " + polyline.getTag().toString(),
                Toast.LENGTH_SHORT).show();
    }
    

    Kotlin

    private val PATTERN_GAP_LENGTH_PX = 20
    private val DOT: PatternItem = Dot()
    private val GAP: PatternItem = Gap(PATTERN_GAP_LENGTH_PX.toFloat())
    
    // Create a stroke pattern of a gap followed by a dot.
    private val PATTERN_POLYLINE_DOTTED = listOf(GAP, DOT)
    
    /**
     * Listens for clicks on a polyline.
     * @param polyline The polyline object that the user has clicked.
     */
    override fun onPolylineClick(polyline: Polyline) {
        // Flip from solid stroke to dotted stroke pattern.
        if (polyline.pattern == null || !polyline.pattern!!.contains(DOT)) {
            polyline.pattern = PATTERN_POLYLINE_DOTTED
        } else {
            // The default pattern is a solid stroke.
            polyline.pattern = null
        }
        Toast.makeText(this, "Route type " + polyline.tag.toString(),
            Toast.LENGTH_SHORT).show()
    }
    

Ajouter des polygones pour représenter des zones sur la carte

Un Polygon est une forme constituée d'une série de coordonnées dans une séquence ordonnée, semblable à une Polyline. La différence réside dans le fait qu'un polygone définit une zone fermée, dont l'intérieur peut être rempli, tandis qu'une polyligne définit une zone ouverte.

  1. Créez un objet PolygonOptions et ajoutez-lui des points. Chaque point représente un emplacement sur la carte, que vous définissez avec un objet LatLng contenant des valeurs de latitude et de longitude. L'exemple de code ci-dessous crée un polygone comportant quatre points.

  2. Rendez le polygone cliquable en appelant la méthode Polygon.setClickable(). Par défaut, les polygones ne sont pas cliquables et votre application ne reçoit pas de notification lorsque l'utilisateur appuie sur un polygone. Les événements de clic sur un polygone se gèrent de la même manière que les événements de clic sur une polyligne, comme expliqué précédemment dans ce tutoriel.

  3. Appelez GoogleMap.addPolygon() pour ajouter le polygone à la carte.

  4. Appelez Polygon.setTag() pour stocker un objet de données avec le polygone. Le code ci-dessous définit un type arbitraire (alpha) pour le polygone.

    Java

    // Add polygons to indicate areas on the map.
    Polygon polygon1 = googleMap.addPolygon(new PolygonOptions()
            .clickable(true)
            .add(
                    new LatLng(-27.457, 153.040),
                    new LatLng(-33.852, 151.211),
                    new LatLng(-37.813, 144.962),
                    new LatLng(-34.928, 138.599)));
    // Store a data object with the polygon, used here to indicate an arbitrary type.
    polygon1.setTag("alpha");
    

    Kotlin

    // Add polygons to indicate areas on the map.
    val polygon1 = googleMap.addPolygon(PolygonOptions()
        .clickable(true)
        .add(
            LatLng(-27.457, 153.040),
            LatLng(-33.852, 151.211),
            LatLng(-37.813, 144.962),
            LatLng(-34.928, 138.599)))
    // Store a data object with the polygon, used here to indicate an arbitrary type.
    polygon1.tag = "alpha"
    // Style the polygon.
    

Ajouter un style personnalisé à votre polygone

Vous pouvez spécifier un certain nombre de propriétés de style dans l'objet PolygonOptions. Les options de style incluent la couleur du trait, la largeur du trait, le motif du trait, les types de jointure et la couleur de remplissage. Si vous ne spécifiez pas de propriété particulière, l'API utilise la valeur par défaut de cette propriété.

Le code suivant applique des couleurs et des motifs de trait spécifiques en fonction du type du polygone, le type étant une propriété arbitraire stockée dans l'objet de données du polygone :

Java

private static final int COLOR_WHITE_ARGB = 0xffffffff;
private static final int COLOR_DARK_GREEN_ARGB = 0xff388E3C;
private static final int COLOR_LIGHT_GREEN_ARGB = 0xff81C784;
private static final int COLOR_DARK_ORANGE_ARGB = 0xffF57F17;
private static final int COLOR_LIGHT_ORANGE_ARGB = 0xffF9A825;

private static final int POLYGON_STROKE_WIDTH_PX = 8;
private static final int PATTERN_DASH_LENGTH_PX = 20;
private static final PatternItem DASH = new Dash(PATTERN_DASH_LENGTH_PX);

// Create a stroke pattern of a gap followed by a dash.
private static final List<PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(GAP, DASH);

// Create a stroke pattern of a dot followed by a gap, a dash, and another gap.
private static final List<PatternItem> PATTERN_POLYGON_BETA =
    Arrays.asList(DOT, GAP, DASH, GAP);

/**
 * Styles the polygon, based on type.
 * @param polygon The polygon object that needs styling.
 */
private void stylePolygon(Polygon polygon) {
    String type = "";
    // Get the data object stored with the polygon.
    if (polygon.getTag() != null) {
        type = polygon.getTag().toString();
    }

    List<PatternItem> pattern = null;
    int strokeColor = COLOR_BLACK_ARGB;
    int fillColor = COLOR_WHITE_ARGB;

    switch (type) {
        // If no type is given, allow the API to use the default.
        case "alpha":
            // Apply a stroke pattern to render a dashed line, and define colors.
            pattern = PATTERN_POLYGON_ALPHA;
            strokeColor = COLOR_DARK_GREEN_ARGB;
            fillColor = COLOR_LIGHT_GREEN_ARGB;
            break;
        case "beta":
            // Apply a stroke pattern to render a line of dots and dashes, and define colors.
            pattern = PATTERN_POLYGON_BETA;
            strokeColor = COLOR_DARK_ORANGE_ARGB;
            fillColor = COLOR_LIGHT_ORANGE_ARGB;
            break;
    }

    polygon.setStrokePattern(pattern);
    polygon.setStrokeWidth(POLYGON_STROKE_WIDTH_PX);
    polygon.setStrokeColor(strokeColor);
    polygon.setFillColor(fillColor);
}

Kotlin

private val COLOR_WHITE_ARGB = -0x1
private val COLOR_DARK_GREEN_ARGB = -0xc771c4
private val COLOR_LIGHT_GREEN_ARGB = -0x7e387c
private val COLOR_DARK_ORANGE_ARGB = -0xa80e9
private val COLOR_LIGHT_ORANGE_ARGB = -0x657db
private val POLYGON_STROKE_WIDTH_PX = 8
private val PATTERN_DASH_LENGTH_PX = 20

private val DASH: PatternItem = Dash(PATTERN_DASH_LENGTH_PX.toFloat())

// Create a stroke pattern of a gap followed by a dash.
private val PATTERN_POLYGON_ALPHA = listOf(GAP, DASH)

// Create a stroke pattern of a dot followed by a gap, a dash, and another gap.
private val PATTERN_POLYGON_BETA = listOf(DOT, GAP, DASH, GAP)

/**
 * Styles the polygon, based on type.
 * @param polygon The polygon object that needs styling.
 */
private fun stylePolygon(polygon: Polygon) {
    // Get the data object stored with the polygon.
    val type = polygon.tag?.toString() ?: ""
    var pattern: List<PatternItem>? = null
    var strokeColor = COLOR_BLACK_ARGB
    var fillColor = COLOR_WHITE_ARGB
    when (type) {
        "alpha" -> {
            // Apply a stroke pattern to render a dashed line, and define colors.
            pattern = PATTERN_POLYGON_ALPHA
            strokeColor = COLOR_DARK_GREEN_ARGB
            fillColor = COLOR_LIGHT_GREEN_ARGB
        }
        "beta" -> {
            // Apply a stroke pattern to render a line of dots and dashes, and define colors.
            pattern = PATTERN_POLYGON_BETA
            strokeColor = COLOR_DARK_ORANGE_ARGB
            fillColor = COLOR_LIGHT_ORANGE_ARGB
        }
    }
    polygon.strokePattern = pattern
    polygon.strokeWidth = POLYGON_STROKE_WIDTH_PX.toFloat()
    polygon.strokeColor = strokeColor
    polygon.fillColor = fillColor
}

En savoir plus sur les motifs de trait et les autres options de personnalisation des formes

Étapes suivantes

Découvrez plus d'informations sur l'objet Cercle. Les cercles sont similaires aux polygones, mais leurs propriétés reflètent la forme d'un cercle.