如何从geojson设置Google Map的功能ID?

时间:2017-04-08 17:43:31

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

如何从geojson设置Google Map's feature's id

idgetId()函数返回的内容。

以下代码不起作用(打印undefined)尽管属性中存在id属性:

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());
  });

小提琴:https://jsfiddle.net/dimskraft/hj2t5je3/5/

UDPATE

我可以写

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

但是这不是错误的Geojson?

1 个答案:

答案 0 :(得分:4)

您应该将第二个参数传递给addGeoJson()方法,该方法定义GeoJSON中的所有内容将用作id。

第二个参数是Data.GeoJsonOptions对象

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

所以改变将是:

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

代码段

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>