为Google地图样式加载外部JSON文件

时间:2017-07-24 18:21:56

标签: javascript json google-maps-api-3

我目前正在使用this site制作的JSON成功设置我的Google地图样式。这里显示了我的代码示例(虽然实际上有数百行json样式):

window.onload = function initMap() {

  var styledMapType = new google.maps.StyledMapType(
    [
      {
        "elementType": "geometry",
        "stylers": [
          {
            "color": "#f5f5f5"
          }
        ]
      },
    ], {name: 'Map'});
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: 51.529517, lng: 10.058284},
    mapTypeControlOptions: {
      mapTypeIds: ['satellite', 'styled_map']
    }
  });

  // Associate the styled map with the MapTypeId and set it to display.
  map.mapTypes.set('styled_map', styledMapType);
  map.setMapTypeId('styled_map');
}
<html>
  <head>
    <script src="load_maps_works.js"></script>
    <style>
       #map{
        position: absolute;
        top: 100px;
        left: 0;
        bottom: 100px;
        right: 0;
    }
    </style>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

显然这会让我的javascript变得一团糟,所以我想把所有的json样式保存在一个单独的.json文件中,这是javascript加载的。不幸的是,我没有太多运气。我试过了:

window.onload = function initMap() {

  function loadJSON(callback) {

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'http://localhost:8000/style.json', true);
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
          }
    };
    xobj.send(null);
  }

  var loaded_json

  loadJSON(function(response) {
    // This correctly prints out the JSON
    loaded_json = JSON.parse(response);
    console.log(loaded_json)
  });

  // This doesn't
  console.log(loaded_json)

  var styledMapType = new google.maps.StyledMapType(loaded_json, {name: 'Map'});

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: 51.529517, lng: 10.058284},
    mapTypeControlOptions: {
      mapTypeIds: ['satellite', 'styled_map']
    }
  });

  //Associate the styled map with the MapTypeId and set it to display.
  map.mapTypes.set('styled_map', styledMapType);
  map.setMapTypeId('styled_map');
}
<html>
  <head>
    <script src="load_maps_broken.js"></script>
    <style>
       #map{
        position: absolute;
        top: 100px;
        left: 0;
        bottom: 100px;
        right: 0;
    }
    </style>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDO1KU-C6Iy7VhyIJMEPiHNtqhWLmYCl3w&libraries=places&sensor=false"></script>
    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

style.json包含的位置:

[
  {
    "elementType": "geometry",
    "stylers": [
      {
        "color": "#ebe3cd"
      }
    ]
  }
]

但是这无法将样式应用于地图。

那么我如何应用外部json文件(托管在我的服务器上)作为我的谷歌地图的样式?它真的像这一切一样复杂吗?

2 个答案:

答案 0 :(得分:1)

将样式存在时,将地图创建移动到loadJSON回调函数中。

live example

代码段(请注意,由于JSON文件不可用,代码段无法在SO上运行,实时示例(external link above)有效):

window.onload = function initMap() {

  function loadJSON(callback) {

    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'style.json', true);
    xobj.onreadystatechange = function() {
      if (xobj.readyState == 4 && xobj.status == "200") {
        callback(xobj.responseText);
      }
    };
    xobj.send(null);
  }

  var loaded_json

  loadJSON(function(response) {
    // This correctly prints out the JSON
    loaded_json = JSON.parse(response);
    console.log(loaded_json)
    var styledMapType = new google.maps.StyledMapType(loaded_json, {
      name: 'Map'
    });

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: {
        lat: 51.529517,
        lng: 10.058284
      },
      mapTypeControlOptions: {
        mapTypeIds: ['satellite', 'styled_map']
      }
    });

    //Associate the styled map with the MapTypeId and set it to display.
    map.mapTypes.set('styled_map', styledMapType);
    map.setMapTypeId('styled_map');
    // This doesn't
    console.log(loaded_json)

  });
}
#map {
  position: absolute;
  top: 100px;
  left: 0;
  bottom: 100px;
  right: 0;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDO1KU-C6Iy7VhyIJMEPiHNtqhWLmYCl3w&libraries=places"></script>
<div id="map"> </div>

答案 1 :(得分:0)

您需要重新安排代码。看起来在styledMapType初始化时loaded_json为空。尝试重新排列代码如下:

var styledMapType;

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: {lat: 51.529517, lng: 10.058284},
  mapTypeControlOptions: {
    mapTypeIds: ['satellite', 'styled_map']
  }
});  

loadJSON(function(response) {
  loaded_json = JSON.parse(response);
  styledMapType = new google.maps.StyledMapType(loaded_json, {name: 'Map'});

  map.mapTypes.set('styled_map', styledMapType);
  map.setMapTypeId('styled_map');
});