首页 > 解决方案 > 使用谷歌地图,如何用某种颜色填充所有国家区域?

问题描述

在我的谷歌地图中,​​我只想显示

  1. 整个地图的背景颜色
  2. 县界以我选择的颜色
  3. 国家区域充满了我选择的颜色
  4. 国家名称标签
  5. 省名标签
  6. 地方(城市)名称的标签

除了 3,我都想通了:

  1. {featureType:'all', elementType: 'geometry', stylers: [{color: '#242f3e'}]}

  2. {featureType: 'administrative.country', elementType: 'geometry.stroke', stylers: [{color: '#242f3e'}]}

  3. ??????我如何做到这一点?????

  4. {feature.type: 'administrative.country', elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}

  5. {feature.type: 'administrative.province', elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}

  6. {feature.type: 'administrative.locality', elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}

但我在实现否时遇到问题。3. 这就是问题所在。

如果您可以测试您在给出的 JSFiddle 中给出的解决方案,那就太好了,因为有时人们给出的建议甚至不起作用。

在此处输入图像描述

标签: javascriptgoogle-mapsgoogle-maps-api-3

解决方案


您需要加载包含所有国家/地区的 GeoJSON 并附加样式。

您可以在此处访问此站点选择所有世界区域并选择例如中等分辨率并构建包含所有世界国家的自定义 GeoJson

您可以根据需要重命名它。我将其重命名为 countries.geo.json。

加载 GoogleMaps 后,导入 GeoJson 并为其附加样式:只需确保此 html 与 country.geo.json 位于同一位置即可。

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 34.397, lng: 150.644},
          zoom: 2
        });
        // here import the GeoJson holding all the countries
        map.data.loadGeoJson('countries.geo.json');
        // here attach a style - I gave red fill and white stroke 
        map.data.setStyle(function(feature) {
            return /** @type {google.maps.Data.StyleOptions} */({
                fillColor: 'red',
                strokeColor: 'white',
                strokeWeight: 2
            });
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY&callback=initMap"
    async defer></script>
  </body>
</html>

最后但并非最不重要的一点是,我想提一下 API 密钥不是我的。我在这里从developers.google.com借来的


推荐阅读