rkleinert
rkleinert

Reputation: 13

Google Maps API: getFeatureById for feature collection not working

I try to change the style of a specific feature of a feature collection data overlay. This is a snippet of my 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
            ]
        ]
        ]
      }
    }

and this is the relevant snippet from my map.js

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

And I am always getting "undefined" in the console.

What am I doing wrong here?

Thanks,

Robert

Upvotes: 0

Views: 3850

Answers (1)

geocodezip
geocodezip

Reputation: 161334

You need to call map.data.getFeatureById(1) inside the callback function (so it doesn't execute before the GeoJson has loaded).

from the documentation:

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

Return Value: None

Loads GeoJS

proof of concept fiddle

code snippet:

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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

Upvotes: 2

Related Questions