Search code examples
javascriptgoogle-mapsgoogle-maps-api-3geojson

Google Maps Javascript API access GeoJSON feature property explicitly


I've been working with the Google Maps Javascript API for several weeks now. I've been having trouble accessing a property of a geoJSON after it has been added to the map and becomes a feature of the map.

For example, lets say I have this sample geoJSON

var geo = {"type":"FeatureCollection","features":[
              {"type":"Feature","id":"country","properties":
                  {"name":"ExampleCountry"},"geometry":  {exampleGeometry}}
          ]};

Lets say I load the geoJSON and want to access the id property of the feature I have just added. Neither feature.id nor feature.getProperty('id') works in this case. From debugging, I found out that I can access the 'id' property via feature.F. That solution was working fine for several weeks, but for whatever reason, last week it ceased to work. I instead have to use feature.K to access the ID property.

var mapOptions = {
      center: { lat: -34.397, lng: 150.644},
      zoom: 8
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), {mapOptions});

 map.data.loadGeoJson(geo);
 map.data.forEach(function(feature) {
     //Used to Work, randomly stopped working last week (feature.F is undefined)
     var id = feature.F;
     //New Solution
     var id = feature.K;
 });

This doesn't seem to be a permanent solution. Does anyone have any idea how this could have happened?


Solution

  • The id of a feature is not a "property" in the meaning of geoJSON.

    There is a getter-method for the id of a feature, use:

     feature.getId()//should return 'country'
    

    When you want to get a property(stored in the properties-member) use e.g.

     feature.getProperty('name')//should return 'ExampleCountry'