Để sử dụng kiểu dựa trên dữ liệu cho ranh giới, bạn phải tạo một mã bản đồ sử dụng bản đồ vectơ JavaScript. Tiếp theo, bạn phải tạo một kiểu bản đồ mới, chọn các lớp đối tượng ranh giới và liên kết kiểu đó với mã bản đồ của bạn.
Tạo mã bản đồ
Để tạo một mã bản đồ mới, hãy làm theo các bước trong phần Tuỳ chỉnh trên đám mây. Đặt Loại bản đồ thành JavaScript rồi chọn tuỳ chọn Véc tơ. Chọn Nghiêng và Xoay để bật chế độ nghiêng và xoay trên bản đồ. Nếu việc sử dụng độ nghiêng hoặc hướng ảnh hưởng tiêu cực đến ứng dụng của bạn, hãy bỏ chọn Độ nghiêng và Xoay để người dùng không thể điều chỉnh các chế độ này.
Trong Google API Console, bạn có thể chọn những lớp đối tượng cần hiển thị. Chế độ này xác định những loại ranh giới sẽ xuất hiện trên bản đồ (ví dụ: địa phương, tiểu bang, v.v.).
Nhấp vào trình đơn thả xuống Lớp đối tượng để thêm hoặc xoá các lớp.
Nhấp vào Lưu để lưu các thay đổi và cung cấp các thay đổi đó cho bản đồ của bạn.
Cập nhật mã khởi chạy bản đồ
Bạn cần có mã bản đồ mà bạn vừa tạo. Bạn có thể tìm thấy thông tin này trên trang Quản lý Maps.
Tải Maps JavaScript API bằng cách thêm trình tải khởi động nội tuyến vào mã ứng dụng của bạn, như minh hoạ trong đoạn mã sau:
<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>
Cung cấp mã bản đồ khi bạn tạo bản đồ bằng cách sử dụng thuộc tính mapId. Đây phải là mã bản đồ mà bạn đã định cấu hình bằng cách sử dụng kiểu bản đồ có các lớp đối tượng được bật.
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.});
Để tham chiếu đến một lớp đối tượng trên bản đồ, hãy gọi map.getFeatureLayer() khi bản đồ khởi tạo:
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');...}
Kiểm tra các chức năng của bản đồ
Tính năng tạo kiểu dựa trên dữ liệu cho ranh giới yêu cầu các chức năng được bật trong Google API Console và được liên kết với một mã bản đồ. Vì mã bản đồ chỉ tồn tại trong thời gian ngắn và có thể thay đổi, nên bạn có thể gọi map.getMapCapabilities() để xác minh xem một chức năng nhất định (ví dụ: tạo kiểu dựa trên dữ liệu) có sẵn hay không trước khi gọi chức năng đó. Đây là bước kiểm tra không bắt buộc.
Ví dụ sau đây cho thấy cách thêm một trình nghe để đăng ký nhận các thay đổi về chức năng bản đồ:
// 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.}});
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-08-27 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)"]]