2017-04-08 30 views
0

如何設置Google Map's feature'sid來自geoj​​son?如何從geojson設置Google地圖的功能ID?

idgetId()函數返回的結果。

雖然在性能存在id屬性下面的代碼無法正常工作(打印undefined):

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?

回答

2

您應該將第二個參數傳遞給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){ 
 
    \t 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>

+0

谷歌關於這方面的文檔並不是非常清晰,但您也可以在使用.loadGeoJson方法時添加選項 – Mackija

相關問題