Dims
Dims

Reputation: 51009

How to set Google Map's feature ID from geojson?

How to set Google Map's feature's id from geojson?

id is what returned by getId() function.

The following code does not work (prints undefined) although id property exists in properties:

var uluru = {lat: -25.363, lng: 131.044};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: uluru
  });
  var data = {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [131.044, -25.363]
    },
    "properties": {
      "Id": 12
    }
  };
  map.data.addGeoJson(data);
  map.data.forEach(function(feature){
    console.log("Id from Google's feature: " + feature.getId());
  });

Fiddle: https://jsfiddle.net/dimskraft/hj2t5je3/5/

UDPATE

I can write

var data = {
    "type": "Feature",
    "id": 13,
    "geometry": {
      "type": "Point",
      "coordinates": [131.044, -25.363]
    },

but won't this be incorrect Geojson?

Upvotes: 1

Views: 3644

Answers (1)

xomena
xomena

Reputation: 32138

You should pass a second parameter to addGeoJson() method that defines what propery in your GeoJSON will be used as id.

The second parameter is Data.GeoJsonOptions object

https://developers.google.com/maps/documentation/javascript/reference#Data.GeoJsonOptions

So the change will be:

map.data.addGeoJson(data, {
    idPropertyName: "Id"
});

Code snippet

function initMap() {
  var uluru = {lat: -25.363, lng: 131.044};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: uluru
  });
  var data = {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [131.044, -25.363]
    },
    "properties": {
      "Id": 12
    }
  };
  map.data.addGeoJson(data, {
    idPropertyName: "Id"
  });
  
  map.data.forEach(function(feature){
  	console.log("Id from Google's feature: " + feature.getId());
  });
}
#map {
  height: 400px;
  width: 100%;
 }
<h3>My Google Maps Demo</h3>
<div id="map"></div>
 <!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap">
</script>

Upvotes: 11

Related Questions