کشیدن چندضلعی روی نقشه

این مثال چندضلعی‌هایی با شکل‌ها و رنگ‌های مختلف را روی نقشه رسم می‌کند.

برای کسب اطلاعات بیشتر، مستندات را ببینید.

شروع کنید

قبل‌از اینکه بتوانید کد نمونه را امتحان کنید، باید محیط توسعه خود را پیکربندی کنید. برای اطلاعات بیشتر، نمونه‌های کد «کیت توسعه نرم‌افزار Google Maps برای Android» را ببینید.

مشاهده کد

Kotlin

override fun onCreate(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)

    val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
    applyInsets(findViewById(R.id.map_container))
}

override fun onMapReady(googleMap: GoogleMap) {
    val fillColorArgb = Color.HSVToColor(
            fillAlphaBar.progress, floatArrayOf(fillHueBar.progress.toFloat(), 1f, 1f))
    val strokeColorArgb = 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.strokeColor xor 0x00ffffff
        }
    }

    // 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)
    }

}

      

جاوا

public class PolygonDemoActivity extends SamplesBaseActivity
        implements OnSeekBarChangeListener, OnItemSelectedListener, OnMapReadyCallback {

    private static final LatLng CENTER = new LatLng(-20, 130);
    private static final int MAX_WIDTH_PX = 100;
    private static final int MAX_HUE_DEGREES = 360;
    private static final int MAX_ALPHA = 255;

    private static final int PATTERN_DASH_LENGTH_PX = 50;
    private static final int PATTERN_GAP_LENGTH_PX = 10;
    private static final Dot DOT = new Dot();
    private static final Dash DASH = new Dash(PATTERN_DASH_LENGTH_PX);
    private static final Gap GAP = new Gap(PATTERN_GAP_LENGTH_PX);
    private static final List<PatternItem> PATTERN_DOTTED = Arrays.asList(DOT, GAP);
    private static final List<PatternItem> PATTERN_DASHED = Arrays.asList(DASH, GAP);
    private static final List<PatternItem> PATTERN_MIXED = Arrays.asList(DOT, GAP, DOT, DASH, GAP);

    private Polygon mutablePolygon;
    private SeekBar fillHueBar;
    private SeekBar fillAlphaBar;
    private SeekBar strokeWidthBar;
    private SeekBar strokeHueBar;
    private SeekBar strokeAlphaBar;
    private Spinner strokeJointTypeSpinner;
    private Spinner strokePatternSpinner;
    private CheckBox clickabilityCheckbox;

    // These are the options for polygon stroke joints and patterns. We use their
    // string resource IDs as identifiers.

    private static final int[] 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,
    };

    private static final int[] 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
    protected void onCreate(Bundle savedInstanceState) {
        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(new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item,
                getResourceStrings(JOINT_TYPE_NAME_RESOURCE_IDS)));

        strokePatternSpinner = findViewById(com.example.common_ui.R.id.strokePatternSpinner);
        strokePatternSpinner.setAdapter(new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item,
                getResourceStrings(PATTERN_TYPE_NAME_RESOURCE_IDS)));

        clickabilityCheckbox = findViewById(com.example.common_ui.R.id.toggleClickability);

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(com.example.common_ui.R.id.map);
        mapFragment.getMapAsync(this);

        applyInsets(findViewById(com.example.common_ui.R.id.map_container));
    }

    @Override
    public void onMapReady(GoogleMap map) {
        // Override the default content description on the view, for accessibility mode.
        map.setContentDescription(getString(com.example.common_ui.R.string.polygon_demo_description));

        int fillColorArgb = Color.HSVToColor(
                fillAlphaBar.getProgress(), new float[]{fillHueBar.getProgress(), 1, 1});
        int strokeColorArgb = Color.HSVToColor(
                strokeAlphaBar.getProgress(), new float[]{strokeHueBar.getProgress(), 1, 1});

        // Create a rectangle with two rectangular holes.
        mutablePolygon = map.addPolygon(new PolygonOptions()
                .addAll(createRectangle(CENTER, 5, 5))
                .addHole(createRectangle(new LatLng(-22, 128), 1, 1))
                .addHole(createRectangle(new LatLng(-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(new GoogleMap.OnPolygonClickListener() {
            @Override
            public void onPolygonClick(Polygon polygon) {
                // Flip the red, green and blue components of the polygon's stroke color.
                polygon.setStrokeColor(polygon.getStrokeColor() ^ 0x00ffffff);
            }
        });
    }

}

      

شبیه‌سازی و اجرای نمونه‌ها

برای اجرای این نمونه به‌صورت محلی، Git لازم است. فرمان زیر مخزن برنامه نمونه را شبیه‌سازی می‌کند.

git clone git@github.com:googlemaps-samples/android-samples.git

پروژه نمونه را به «استودیو Android» وارد کنید:

  1. در «استودیو Android»، فایل > جدید > وارد کردن پروژه را انتخاب کنید.
  2. به مکانی که مخزن را ذخیره کرده‌اید بروید و دایرکتوری پروژه را برای Kotlin یا Java انتخاب کنید:

    • Kotlin: PATH-REPO/android-samples/ApiDemos/kotlin
    • Java: PATH-REPO/android-samples/ApiDemos/java
  3. باز کردن را انتخاب کنید. «استودیو Android» بااستفاده از ابزار ساخت Gradle پروژه شما را می‌سازد.
  4. فایل secrets.properties خالی در همان پوشه فایل local.properties پروژه‌تان ایجاد کنید. برای کسب اطلاعات بیشتر درباره این فایل، به افزودن کلید API به پروژه مراجعه کنید.
  5. کلید میانای برنامه‌سازی کاربردی را از پروژه‌تان با کیت توسعه نرم‌افزار Google Maps برای Android فعال‌شده دریافت کنید.
  6. رشته زیر را به secrets.properties اضافه کنید و YOUR_API_KEY را با مقدار کلید میانای برنامه‌سازی کاربردی خود جایگزین کنید:

    MAPS_API_KEY=YOUR_API_KEY
  7. برنامه را اجرا کنید.