1

ハードコーディングされた値を持つ関数を使用して、リーフレット マップ上のポリゴンに色を割り当てています。スタイリング関数は a 内から呼び出されます$.getJSON。値がハードコードされているのではなく、データから直接取得されるようにコードを書き直したい - 理論的には、これは将来コードをより簡単に再利用できるようにするためです

によって呼び出される (切り捨てられた) geojson データ$.getJSONは次のとおりです。

{"type": "FeatureCollection","crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [{"type": "Feature", "properties": {"MAJORCOLOR": "ZONE A"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.946264290220981, 42.574112051418197 ], [ -77.954525714402251, 42.569801987122105 ], [ -77.964847297117899, 42.562124252064194 ]]]}},  
"features": [{"type": "Feature", "properties": {"MAJORCOLOR": "ZONE B"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.946264290220981, 42.574112051418197 ], [ -77.954525714402251, 42.569801987122105 ], [ -77.964847297117899, 42.562124252064194 ]]]}},
"features": [{"type": "Feature", "properties": {"MAJORCOLOR": "ZONE A"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.946264290220981, 42.574112051418197 ], [ -77.954525714402251, 42.569801987122105 ], [ -77.964847297117899, 42.562124252064194 ]]]]}}]}

$.getJSON

$.getJSON('data/ecozone_wgs84_multipart.geojson', function(data){
var geojsonLayer = L.geoJson(data.features, {  
    onEachFeature: makeMarkers,
    //this provides thematic styling to the layers
    style: style
})
.addTo(map);  

//call the function to create keys
getArray(data);
});

これは、データ値に基づいて色を割り当てる関数です

//get color depending on the Zone value
function getColor(z) {
return  z == 'ZONE A' ? '#a6cee3':
        z == 'ZONE B' ? '#1f78b4':
        z == 'ZONE C' ? '#b2df8a':
'#000000';}

styleこれは、内部から関数によって呼び出されます$.getJSON

function style(feature) {
return {
    fillColor: getColor(feature.properties.MAJORCOLOR),
    color: getColor(feature.properties.MAJORCOLOR),
    weight: 1.25,
    opacity: 0.95,
    fillOpacity: 0.5
};}

getColor色を決定する値をハードコードする代わりに、次のように記述した geojson から作成した配列から値を取得するように、関数を書き直したいと思います。

//this is a function that pulls the values from MAJORCOLOR to create the array
function getArray(data) {
for (var i=0; i< data.features.length; i++) {
keys.push(data.features[i].properties.MAJORCOLOR);
}}

//this is a function to collapse to unique values
function unique(keys) {
return keys.reduce(function(p, c) {
    if (p.indexOf(c) < 0) p.push(c);
    return p;
}, []);};

ただし、代わりに配列の値を使用するようにカラー関数を書き直すと、機能しません。ポリゴンには、必要な色ではなく、すべて「else」カラー #000000 が割り当てられます。

function getColor(z) {
return  z == unique(keys)[0] ? '#a6cee3':
        z == unique(keys)[1] ? '#1f78b4':
        z == unique(keys)[2] ? '#b2df8a':
        '#000000';}

これが機能しないのはなぜですか?

unique(keys)コンソールから見ると、ちゃんと["ZONE A", "ZONE B", "ZONE C"]作成していることがわかりkeysます...困惑しています。

私の質問に長々と答えてくれてありがとう!

4

1 に答える 1