Untuk menggunakan gaya visual berbasis data untuk batas, Anda harus membuat ID peta yang menggunakan peta vektor JavaScript. Selanjutnya, Anda harus membuat gaya peta baru, memilih lapisan fitur batas, dan mengaitkan gaya tersebut dengan ID peta Anda.
Membuat ID peta
Untuk membuat ID peta baru, ikuti langkah-langkah di bagian Penyesuaian cloud.
Tetapkan jenis Peta ke JavaScript, dan pilih opsi Vector.
Centang Tilt dan Rotation untuk mengaktifkan kemiringan dan rotasi pada peta. Jika penggunaan kemiringan atau arah berdampak buruk pada aplikasi Anda, jangan centang Tilt dan Rotation agar pengguna tidak dapat menyesuaikannya.
Di Konsol API Google Anda dapat memilih lapisan fitur mana yang akan ditampilkan. Lapisan ini menentukan jenis batas yang akan muncul di peta (misalnya lokalitas, negara bagian, dan sebagainya).
Klik drop-down Feature layers untuk menambahkan atau menghapus lapisan.
Klik Save untuk menyimpan perubahan dan menyediakannya untuk peta Anda.
Memperbarui kode inisialisasi peta
Tindakan ini memerlukan ID peta yang baru saja Anda buat. ID ini dapat ditemukan di halaman Map Management.
Muat Maps JavaScript API dengan menambahkan loader bootstrap inline ke kode aplikasi Anda, seperti yang ditunjukkan dalam cuplikan berikut:
<script>
(g=>{varh,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});vard=b.maps||(b.maps={}),r=newSet,e=newURLSearchParams,u=()=>h||(h=newPromise(async(f,n)=>{await(a=m.createElement("script"));e.set("libraries",[...r]+"");for(king)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:"YOUR_API_KEY",v:"weekly",// Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).// Add other bootstrap parameters as needed, using camel case.});
</script>
Berikan ID peta saat Anda membuat instance peta menggunakan properti mapId.
ID ini harus berupa ID peta yang Anda konfigurasi menggunakan gaya peta dengan lapisan fitur yang diaktifkan.
map=newgoogle.maps.Map(document.getElementById('map'),{center:{lat:-34.397,lng:150.644},zoom:8,mapId:'MAP_ID'// A map ID using a style with one or more feature layers enabled.});
Untuk mendapatkan referensi ke lapisan fitur pada peta Anda, panggil map.getFeatureLayer() saat peta melakukan inisialisasi:
functioninitMap(){map=newgoogle.maps.Map(document.getElementById("map"),{center:{lat:20.773,lng:-156.01},zoom:12,mapId:'MAP_ID',});// Add a feature layer for localities.localityLayer=map.getFeatureLayer('LOCALITY');...}
Memeriksa kemampuan peta
Gaya visual berbasis data untuk batas memerlukan kemampuan yang diaktifkan di Konsol API Google, dan dikaitkan dengan ID peta. Karena ID peta bersifat sementara dan dapat berubah sewaktu-waktu, Anda dapat memanggil map.getMapCapabilities() untuk memverifikasi apakah kemampuan tertentu (misalnya, gaya visual berbasis data) tersedia sebelum memanggilnya. Pemeriksaan ini bersifat opsional.
Contoh berikut menunjukkan penambahan pemroses untuk memonitor perubahan kemampuan peta:
// subscribe to changesmap.addListener('mapcapabilities_changed',()=>{constmapCapabilities=map.getMapCapabilities();if(!mapCapabilities.isDataDrivenStylingAvailable){// Data-driven styling is *not* available, add a fallback.// Existing feature layers are also unavailable.}});
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Informasi yang saya butuhkan tidak ada","missingTheInformationINeed","thumb-down"],["Terlalu rumit/langkahnya terlalu banyak","tooComplicatedTooManySteps","thumb-down"],["Sudah usang","outOfDate","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Masalah kode / contoh","samplesCodeIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-09-05 UTC."],[[["\u003cp\u003eData-driven styling for boundaries requires a JavaScript vector map with a custom style associated with a map ID.\u003c/p\u003e\n"],["\u003cp\u003eYou can select specific boundary feature layers (like localities or states) to display in the Google API Console to optimize performance.\u003c/p\u003e\n"],["\u003cp\u003eInitialize your map with the designated map ID and API key, ensuring they are linked to the same Google Cloud project.\u003c/p\u003e\n"],["\u003cp\u003eUtilize \u003ccode\u003emap.getFeatureLayer()\u003c/code\u003e to access and interact with specific feature layers on your map.\u003c/p\u003e\n"],["\u003cp\u003eVerify the availability of data-driven styling by using \u003ccode\u003emap.getMapCapabilities()\u003c/code\u003e before implementation.\u003c/p\u003e\n"]]],["To utilize data-driven styling for boundaries, first, create a JavaScript vector map ID in the Google API Console. Next, create a new map style and associate it with the map ID, selecting the desired boundary feature layers. Then, update your map initialization code with the new map ID. Ensure your map ID and API key are linked to the same project. Finally, use `map.getFeatureLayer()` to reference feature layers and `map.getMapCapabilities()` to check styling availability.\n"],null,["Select platform: [Android](/maps/documentation/android-sdk/dds-boundaries/start \"View this page for the Android platform docs.\") [iOS](/maps/documentation/ios-sdk/dds-boundaries/start \"View this page for the iOS platform docs.\") [JavaScript](/maps/documentation/javascript/dds-boundaries/start \"View this page for the JavaScript platform docs.\")\n\n\u003cbr /\u003e\n\nTo use data-driven styling for boundaries you must create a map ID that uses the\nJavaScript vector map. Next, you must create a new map style, select the\nboundary feature layers, and associate the style with your map ID.\n\nCreate a map ID\n\nTo create a new [map ID](/maps/documentation/get-map-id), follow the steps in\n[Cloud customization](/maps/documentation/javascript/cloud-customization).\nSet the Map type to **JavaScript** , and select the **Vector** option.\nCheck **Tilt** and **Rotation** to enable tilt and rotation on the map. If\nthe use of tilt or heading adversely affects your app, leave **Tilt** and\n**Rotation** un-checked so users cannot adjust them.\n\nCreate a new map style\n\nTo create a new map style, follow the instructions in\n[Manage map styles](/maps/documentation/javascript/cloud-customization/map-styles-leg)\nto create the style, and\n[associate the style with the map ID you just created](/maps/documentation/javascript/cloud-customization/map-styles-leg#associate-style-with-map-id).\n| **Experimental:** This feature can only be set for light map styles. When you link a light map style that has this feature enabled to a [map\n| ID](../map-ids/mapid-over), the enabled layers are also available for the dark map style.\n\nSelect feature layers\n\nIn the Google API Console you can select which feature layers to display. This\ndetermines which kinds of boundaries will appear on the map (for example\nlocalities, states, and so on).\n| **Important:** For optimal performance, only select the layers you need.\n\nTo manage feature layers\n\n1. In the Google API Console, [go to the Map Styles page](https://console.cloud.google.com/project/_/google/maps-apis/studio/styles).\n2. Select a project if prompted.\n3. Select a map style.\n4. Click the **Feature layers** drop-down to add or remove layers.\n5. Click **Save** to save your changes and make them available to your maps.\n\nUpdate your map initialization code\n\nThis requires the map ID you just created. It can be found on your [Maps\nManagement](https://console.cloud.google.com/google/maps-apis/studio/maps) page.\n| **Important:** Your map ID and API key must be associated with the same Google Cloud console project. Likewise, the map ID must be associated with a map style with one or more feature layers enabled.\n\n1. Load the Maps JavaScript API by adding the inline bootstrap loader to your application code, as shown in the following snippet:\n\n```javascript\n\u003cscript\u003e\n (g=\u003e{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=()=\u003eh||(h=new Promise(async(f,n)=\u003e{await (a=m.createElement(\"script\"));e.set(\"libraries\",[...r]+\"\");for(k in g)e.set(k.replace(/[A-Z]/g,t=\u003e\"_\"+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=()=\u003eh=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)=\u003er.add(f)&&u().then(()=\u003ed[l](f,...n))})({\n key: \"YOUR_API_KEY\",\n v: \"weekly\",\n // Use the 'v' parameter to indicate the /maps/documentation/javascript/versions to use (weekly, beta, alpha, etc.).\n // Add other /maps/documentation/javascript/load-maps-js-api#required_parameters as needed, using camel case.\n });\n\u003c/script\u003e\n```\n| **Note:** As the developer of a Maps JavaScript API application it is your responsibility to verify that your application complies with local laws by verifying that the correct region localization is applied for the country in which the application is hosted.\n\n1. Provide a map ID when you instantiate the map using the `mapId` property.\n This should be the map ID that you configured using a map style with feature\n layers enabled.\n\n ```javascript\n map = new\n google.maps.Map(document.getElementById('map'), {\n center: {lat: -34.397, lng: 150.644},\n zoom: 8,\n mapId: '\u003cvar translate=\"no\"\u003eMAP_ID\u003c/var\u003e' // A map ID using a style with one or more feature layers enabled.\n });\n ```\n\nLearn more about [loading the Maps JavaScript API](/maps/documentation/javascript/load-maps-js-api).\n\nAdd feature layers to a map\n\nTo get a reference to a feature layer on your map, call `map.getFeatureLayer()`\nwhen the map initializes: \n\n```javascript\nfunction initMap() {\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: { lat: 20.773, lng: -156.01 },\n zoom: 12,\n mapId: 'MAP_ID',\n });\n\n // Add a feature layer for localities.\n localityLayer = map.getFeatureLayer('LOCALITY');\n ...\n}\n```\n\nCheck map capabilities\n\nData-driven styling for boundaries requires capabilities which are enabled in the\nGoogle API Console, and associated with a map ID. Because map IDs are ephemeral\nand subject to change, you can call `map.getMapCapabilities()`\nto verify whether a certain capability (for example data-driven styling) is\navailable prior to calling it. This check is optional.\n\nThe following example shows adding a listener to subscribe to map capability\nchanges: \n\n```javascript\n// subscribe to changes\nmap.addListener('mapcapabilities_changed', () =\u003e {\n const mapCapabilities = map.getMapCapabilities();\n\n if (!mapCapabilities.isDataDrivenStylingAvailable) {\n // Data-driven styling is *not* available, add a fallback.\n // Existing feature layers are also unavailable.\n }\n});\n```\n\nNext steps\n\n- [Style a boundary polygon](/maps/documentation/javascript/dds-boundaries/style-polygon)\n- [Make a choropleth map](/maps/documentation/javascript/dds-boundaries/choropleth-map)\n- [Handle mouse events](/maps/documentation/javascript/dds-boundaries/handle-events)\n- [Get a place ID for a region](/maps/documentation/javascript/dds-boundaries/dds-use-maps-places-apis#use_to_find_a_region)\n- [Use the Geocoding and Places APIs with data-driven styling for boundaries](/maps/documentation/javascript/dds-boundaries/dds-use-maps-places-apis)"]]