使用setMap的Google Maps forEach设置折线可见性(错误:setMap不是函数)

时间:2018-03-17 19:08:40

标签: javascript google-maps-api-3

我正在尝试根据属性设置折线的可见性。我使用forEach迭代GeoJson数据中的功能但是当我尝试在数组上调用setMap时,我得到类型错误:setMap不是函数。我也尝试将结果特征推送到具有相同结果的新数组中。

map.data.loadGeoJson(
  'data/trails2018.geojson', {},
  function(features) {
    console.log("loadGeoJson callback "+features.length);
    map.data.forEach(function(feature) {
      var skill = feature.getProperty('skill_leve');
        if (skill == 'ADVANCED'){ 
            feature.setMap(null);
        }
    }); 
  });

1 个答案:

答案 0 :(得分:0)

您可以使用样式属性visible控制Data Layer上的要素的可见性。

  map.data.setStyle(function(feature) {
    var visible = false;
    if (feature.getProperty('skill_level')) {
      var skill = feature.getProperty('skill_level');
      if (skill == 'ADVANCED') {
        visible = true;
      }
    }
    return /** @type {google.maps.Data.StyleOptions} */ ({
      strokeColor: "blue",
      visible: visible
    });
  });

proof of concept fiddle

代码段

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(-23.55865, -46.65953),
      zoom: 5,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var features = map.data.addGeoJson(geoJson);
  console.log("addGeoJson returns " + features.length);
  map.data.forEach(function(feature) {
    var skill = feature.getProperty('skill_level');
    if (skill == 'ADVANCED') {
      // feature.setMap(null);
    }
  });
  map.data.setStyle(function(feature) {
    var visible = false;
    if (feature.getProperty('skill_level')) {
      var skill = feature.getProperty('skill_level');
      if (skill == 'ADVANCED') {
        visible = true;
      }
    }
    return /** @type {google.maps.Data.StyleOptions} */ ({
      strokeColor: "blue",
      visible: visible
    });
  });
}
google.maps.event.addDomListener(window, "load", initialize);
var geoJson = {
  "type": "FeatureCollection",
  "features": [{
      "type": "Feature",
      "properties": {
        "id": 1,
        "skill_level": "ADVANCED"
      },
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [-43.48283, -23.02487],
          [-43.65903, -23.55888]
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "id": 2,
        "skill_level": "BEGINNER"
      },
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [-46.65953, -23.02487],
          [-46.65903, -23.55888]
        ]
      }
    }
  ]
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>