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

Dim*_*ims 0 javascript google-maps geojson google-maps-api-3

如何从geojson 设置Google Map的功能 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());
  });
Run Code Online (Sandbox Code Playgroud)

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

UDPATE

我会写

var data = {
    "type": "Feature",
    "id": 13,
    "geometry": {
      "type": "Point",
      "coordinates": [131.044, -25.363]
    },
Run Code Online (Sandbox Code Playgroud)

但这不是错误的Geojson吗?

xom*_*ena 5

您应该将第二个参数传递给addGeoJson()方法,该方法定义您的GeoJSON中的哪些属性将用作ID。

第二个参数是Data.GeoJsonOptions对象

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

因此更改将是:

map.data.addGeoJson(data, {
    idPropertyName: "Id"
});
Run Code Online (Sandbox Code Playgroud)

程式码片段

map.data.addGeoJson(data, {
    idPropertyName: "Id"
});
Run Code Online (Sandbox Code Playgroud)
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());
  });
}
Run Code Online (Sandbox Code Playgroud)
#map {
  height: 400px;
  width: 100%;
 }
Run Code Online (Sandbox Code Playgroud)