【问题标题】:Google Maps API will not display GeoJSON dataGoogle Maps API 不会显示 GeoJSON 数据
【发布时间】:2019-05-07 19:12:44
【问题描述】:

我第一次尝试从 GeoJSON 文件中提取数据并将其显示在 Google 地图中。我只想在 geojson 的坐标处放置一个简单的谷歌地图标记。尝试在网上阅读有关 GM API 和 geojson 的内容,但我觉得我错过了一些非常简单的东西。

这是主地图代码

<script>
var map;
  function initMap()
  {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 16,
      center: new google.maps.LatLng(32.061146,34.799387),
      mapTypeId: 'hybrid'
    });
  }
map.data.loadGeoJson('toilets.geojson');
map.data.setMap(map);
</script>

这是 toilets.geojson 文件:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
          "coordinates": [
            34.799339175224304,
            32.061136963943106
          ]
      }
    }]
}

只希望在这些坐标处出现一个常规标记

【问题讨论】:

    标签: google-maps-api-3 geojson


    【解决方案1】:

    一个问题是当您加载 GeoJSON 时,map 变量超出范围。该代码需要在initMap 函数中。

    <script>
    var map;
      function initMap()
      {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 16,
          center: new google.maps.LatLng(32.061146,34.799387),
          mapTypeId: 'hybrid'
        });
        map.data.loadGeoJson('toilets.geojson');
        map.data.setMap(map);
      }
    </script>
    

    var map;
    
    function initMap() {
      map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: new google.maps.LatLng(32.061146, 34.799387),
        mapTypeId: 'hybrid'
      });
      map.data.addGeoJson(geoJsonData);
      map.data.setMap(map);
    }
    var geoJsonData = {
      "type": "FeatureCollection",
      "features": [{
        "type": "Feature",
        "properties": {},
        "geometry": {
          "type": "Point",
          "coordinates": [
            34.799339175224304,
            32.061136963943106
          ]
        }
      }]
    };
    html,
    body,
    #map {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <div id="map"></div>
    <!-- Replace the value of the key parameter with your own API key. -->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多