向数据层添加几何 - 如何在添加期间设置要素样式?

时间:2018-05-26 00:08:48

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

我正在建立一个学校图层。对于每所学校,我将根据其属性分配不同的图标。

这是我目前的解决方案。我首先将所有学校插入数据层,然后运行forEach函数来更改每个点的图标。这不是最佳选择,因为我正在添加学校,然后立即编辑学校。

// Current solution.  It is WORKING but it is not optimal

schools = (a list of google.maps.Data.Point objects)

for (school in schools) {
    schoolLayer.add({
        geometry: school,
    });
}

schoolLayer.forEach(function(feature) {
    schoolLayer.overrideStyle(feature, {
        if (some condition) {
            icon: ...
        } else {
            icon: ...
        }
    }
}

最佳解决方案是在添加样式时为学校添加样式,以便之后不需要编辑。像这样:

// The solution I am trying to achieve.  The `StyleOptions` property is made up to represent what I am trying to achieve.  I want to add styles to the school as it is being inserted into the data layer

for (school in schools) {
    schoolLayer.add({
        geometry: school,
        StyleOptions: {
            if (some condition) {
                icon: ...
            } else {
                icon: ...
            }
        }
    });
}

上述代码不起作用。文档中是否有我遗漏的内容可以让我实现这一目标?

1 个答案:

答案 0 :(得分:1)

我建议创建一个google.maps.Data.Feature对象列表,而不是google.maps.Data.Point个对象。 Data.Feature可以包含几何形状,在您的情况下是google.maps.Data.Point的实例,id可以是字符串或数字,属性可以放置名称 - 值对。

https://developers.google.com/maps/documentation/javascript/reference/3/data#Data.Feature

特征中存在属性是一种技巧。您可以为数据层应用样式函数,该函数读取要素的属性(在您的案例中为图标)并返回相应的样式。将要素添加到数据图层时,将应用样式功能。

查看以下代码示例,schoolLayer.setStyle()是最相关的部分

var map;
function initMap() {
  var schools = [
      new google.maps.Data.Feature({
        geometry: new google.maps.Data.Point({lat: 41.384301, lng: 2.173792}),
        id: 1,
        properties: {
          "icon": "http://maps.google.com/mapfiles/kml/paddle/blu-blank.png"
        }
      }),
      new google.maps.Data.Feature({
        geometry: new google.maps.Data.Point({lat: 41.384897, lng: 2.176656}),
        id: 2,
        properties: {
          "icon": "http://maps.google.com/mapfiles/kml/paddle/pink-blank.png"
        }
      }),
      new google.maps.Data.Feature({
        geometry: new google.maps.Data.Point({lat: 41.386756, lng: 2.175268}),
        id: 3,
        properties: {
          "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png"
        }
      })
  ];

  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 17,
    center: {lat: 41.385064, lng: 2.173403}
  });

  var schoolLayer = map.data;
  schoolLayer.setStyle(function(feature){
    return {
        icon: feature.getProperty("icon"),
        title: "" + feature.getId()
    };
  });

  for (school of schools) {
    schoolLayer.add(school);
  }
}
#map {
  height: 100%;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap">

你也可以在jsfiddle上找到这个例子:https://jsfiddle.net/xomena/tLsjkowp/

我希望这有帮助!