Sınır poligonuna stil uygulama

Platform seçin: Android iOS JavaScript

Genel Bakış

Sınır poligonunun dolgusunu ve konturunu biçimlendirmek için FeatureStyleOptions kullanarak stil özelliklerini tanımlayın ve özellik katmanındaki style özelliğini, stil mantığını içeren bir google.maps.FeatureStyleFunction olarak ayarlayın.

Aşağıdaki örnek haritada, tek bir bölge için sınır poligonunun vurgulanması gösterilmektedir.

style özelliğini, stil mantığı içerebilen bir google.maps.FeatureStyleFunction değerine ayarlayarak sınır özelliklerine stil uygulayın. Stil işlevi, etkilenen özellik katmanındaki her özellik üzerinde çalıştırılır ve stil özelliğini ayarladığınızda uygulanır. Güncellemek için stil özelliğini tekrar ayarlamanız gerekir.

Bir özellik katmanındaki tüm özellikleri tek tip olarak biçimlendirmek için style özelliğini google.maps.FeatureStyleOptions olarak ayarlayın. Bu durumda, mantık gerekmediği için özellik stili işlevi kullanmanız gerekmez.

Stil işlevi, özelliklere uygulandığında her zaman tutarlı sonuçlar döndürmelidir. Örneğin, bir dizi özelliği rastgele renklendirmek istiyorsanız rastgele kısım, özellik stili işlevinde yer almamalıdır. Aksi takdirde istenmeyen sonuçlar ortaya çıkabilir.

Bu işlev bir katmandaki her özellik üzerinde çalıştığından optimizasyon önemlidir. Oluşturma sürelerinin etkilenmesini önlemek için:

  • Yalnızca ihtiyacınız olan katmanları etkinleştirin.
  • Bir katman artık kullanılmadığında style değerini null olarak ayarlayın.

Yerleşim yeri özellik katmanındaki bir poligonu stillendirmek için aşağıdaki adımları uygulayın:

  1. Henüz yapmadıysanız yeni bir harita kimliği ve harita stili oluşturmak için Başlangıç bölümündeki adımları uygulayın. Yerleşim yeri özellik katmanını etkinleştirdiğinizden emin olun.
  2. Harita başlatıldığında yerleşim yeri özellik katmanına referans alın.

    TypeScript

    // Get the feature layer.
    featureLayer = innerMap.getFeatureLayer('LOCALITY');

    JavaScript

    // Get the feature layer.
    featureLayer = innerMap.getFeatureLayer('LOCALITY');

  3. google.maps.FeatureStyleFunction türünde bir stil tanımı oluşturun.

  4. Özellik katmanındaki style özelliğini FeatureStyleFunction olarak ayarlayın. Aşağıdaki örnekte, yalnızca eşleşen yer kimliğine sahip google.maps.Feature için stil uygulayacak bir işlevin nasıl tanımlanacağı gösterilmektedir:

    TypeScript

    // Define a style with purple fill and border.
    const featureStyleOptions: google.maps.FeatureStyleOptions = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5,
    };
    
    // Apply the style to a single boundary.
    featureLayer.style = (options: google.maps.FeatureStyleFunctionOptions) => {
        const feature = options.feature as google.maps.PlaceFeature;
        if (feature.placeId === 'ChIJ0zQtYiWsVHkRk8lRoB1RNPo') {
            // Hana, HI
            return featureStyleOptions;
        }
        return null;
    };

    JavaScript

    // Define a style with purple fill and border.
    const featureStyleOptions = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5,
    };
    
    // Apply the style to a single boundary.
    featureLayer.style = (options) => {
        const feature = options.feature;
        if (feature.placeId === 'ChIJ0zQtYiWsVHkRk8lRoB1RNPo') {
            // Hana, HI
            return featureStyleOptions;
        }
        return null;
    };

Belirtilen yer kimliği bulunamazsa veya seçilen özellik türüyle eşleşmezse stil uygulanmaz. Örneğin, "New York"un yer kimliğiyle eşleşen bir POSTAL_CODE katmanına stil uygulamaya çalışırsanız stil uygulanmaz.

Bir katmandan stil kaldırma

Bir katmandan stil kaldırmak için style değerini null olarak ayarlayın:

featureLayer.style = null;

Özellikleri hedeflemek için yer kimliklerini arama

Bölgelerin yer kimliklerini almak için:

Kapsam bölgeye göre değişir. Ayrıntılar için Google sınır kapsamı başlıklı makaleyi inceleyin.

Coğrafi adlar, USGS Board on Geographic Names ve U.S. Gazetteer Files gibi birçok kaynaktan alınabilir.

Eksiksiz örnek kod

TypeScript

let featureLayer: google.maps.FeatureLayer;

async function init() {
    // Request needed libraries.
    await google.maps.importLibrary('maps');

    // Get the gmp-map element.
    const mapElement = document.querySelector('gmp-map')!;

    // Get the inner map.
    const innerMap = mapElement.innerMap;

    // Get the feature layer.
    featureLayer = innerMap.getFeatureLayer('LOCALITY');

    // Define a style with purple fill and border.
    const featureStyleOptions: google.maps.FeatureStyleOptions = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5,
    };

    // Apply the style to a single boundary.
    featureLayer.style = (options: google.maps.FeatureStyleFunctionOptions) => {
        const feature = options.feature as google.maps.PlaceFeature;
        if (feature.placeId === 'ChIJ0zQtYiWsVHkRk8lRoB1RNPo') {
            // Hana, HI
            return featureStyleOptions;
        }
        return null;
    };
}

void init();

JavaScript

let featureLayer;

async function init() {
    // Request needed libraries.
    await google.maps.importLibrary('maps');

    // Get the gmp-map element.
    const mapElement = document.querySelector('gmp-map');

    // Get the inner map.
    const innerMap = mapElement.innerMap;

    // Get the feature layer.
    featureLayer = innerMap.getFeatureLayer('LOCALITY');

    // Define a style with purple fill and border.
    const featureStyleOptions = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5,
    };

    // Apply the style to a single boundary.
    featureLayer.style = (options) => {
        const feature = options.feature;
        if (feature.placeId === 'ChIJ0zQtYiWsVHkRk8lRoB1RNPo') {
            // Hana, HI
            return featureStyleOptions;
        }
        return null;
    };
}

void init();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
gmp-map {
    height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}

HTML

<html>
    <head>
        <title>Boundaries Simple</title>

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
        <script>
            // prettier-ignore
            (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
                key: "GOOGLE_MAPS_API_KEY"
            });
        </script>
    </head>
    <body>
        <gmp-map
            center="20.773,-156.01"
            zoom="12"
            map-id="8b37d7206ccf0121d4414bb0"></gmp-map>
    </body>
</html>

Örneği deneyin