Google Maps API:getFeatureById功能集合无效

时间:2016-10-04 12:33:32

标签: javascript google-maps geojson

我尝试更改要素集合数据叠加层的特定要素的样式。这是我的json片段:



{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": 1,
      "properties": {
        "name": "1 CBD - Bankenviertel",
        "color": "transparent",
        "isHovered": false,
        "isActive": false
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              8.67279430349,
              50.1143807311
            ],
            [
              8.67280054398,
              50.1143975981
            ]
        ]
        ]
      }
    }




这是我map.js的相关摘录



map.data.loadGeoJson('some.json');
console.log(map.data.getFeatureById(1));




我总是得到"未定义"在控制台中。

我在这里做错了什么?

谢谢,

罗伯特

1 个答案:

答案 0 :(得分:1)

你需要在回调函数中调用map.data.getFeatureById(1)(因此它在GeoJson加载之前不会执行)。

来自the documentation

  

loadGeoJson (url:string,options?:Data.GeoJsonOptions, callback?:function(Array)

     

返回值:无

     

加载GeoJS

proof of concept fiddle

代码段

var geocoder;
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      zoom: 4,
      center: {
        lat: -28,
        lng: 137
      },
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  // map.data.addGeoJson(geoJson);
  map.data.loadGeoJson(
    'https://api.myjson.com/bins/1teyu', {},
    function(features) {
      console.log(map.data.getFeatureById(1));
      console.log(map.data.getFeatureById(1).getProperty("letter"));
    });
}
google.maps.event.addDomListener(window, "load", initialize);
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>