如何从react props添加数据属性到离线传单地图?

时间:2017-03-14 09:16:10

标签: javascript reactjs leaflet

我正在使用Leaflet作为网站的离线地图。基本上,我通过从一个大的(13.000行)javascript文件中导入这些国家来映射这些代码:http://codepen.io/dagmara223/pen/jydMqy

然而,我根据作为反应道具传递的数据输入为每个国家着色特定颜色。

我输入了dataratio的数据结构,但也可以使用注释掉的代码访问它。

这是我的worldmap.js

import React from 'react';
import L from 'leaflet';
import countries from './countries.js';

var Worldmap = React.createClass({


    getInitialState: function(){
        let geolocation =  [];

        // let dataratio = this.props.data;

        let dataratio =  {
                "JPN": "25",
                "RUS": "91",
                "SWE": "67",
                "NOR": "82",
                "USA": "13"
            };

        navigator.geolocation.getCurrentPosition(function(position) {
            let lat = position.coords.latitude;
            let lon = position.coords.longitude;


            if(lat != null && lon != null) // If we can get latitude and longitude, reset geolocation and push values.
                geolocation.length = 0;
                geolocation.push(lat, lon);
            if(!lat || !lon) // If we can't get latitude or longitude, set a default value.
                geolocation = [0,0];

            let map = L.map('leafletmap').setView(geolocation, 3); // Map will center on geolocation, on zoom level 3 per default.

            let info = L.control();

            info.onAdd = function (map) {
                this._div = L.DomUtil.create('div', 'info');
                this.update();
                return this._div;
            };

            info.update = function (props) {
                this._div.innerHTML = '<h4>Data ratio</h4>' +  (props ?
                    '<b>' + props.name + '</b><br />' + props.data + ' ratio'
                        : 'Hover over a country');
            };

            info.addTo(map);


            function getColor(d) {
                return d > 90 ? '#4a1486' :
                    d > 75  ? '#6a51a3' :
                        d > 50  ? '#807dba' :
                            d > 25  ? '#9e9ac8' :
                                d > 15   ? '#bcbddc' :
                                    d > 5   ? '#dadaeb' :
                                        d > 1   ? '#f2f0f7' :
                                            '#D3D3D3'; // Default color of data doesn't exist or is 0.
            }

            function style(feature) {
                return {
                    weight: 2,
                    opacity: 1,
                    color: 'white',
                    fillOpacity: 1,
                    fillColor: getColor(feature.properties.data) // That's where we get the ratio if it exists in the country
                };
            }

            function highlightFeature(e) {
                let layer = e.target;

                layer.setStyle({
                    weight: 5,
                    color: '#666',
                    fillOpacity: 0.7
                });

                if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
                    layer.bringToFront();
                }

                info.update(layer.feature.properties);
            }

            let geojson;

            function resetHighlight(e) {
                geojson.resetStyle(e.target);
                info.update();
            }

            function zoomToFeature(e) {
                map.fitBounds(e.target.getBounds());
            }

            function onEachFeature(feature, layer) {
                layer.on({
                    mouseover: highlightFeature,
                    mouseout: resetHighlight,
                    click: zoomToFeature
                });
            }


            geojson = L.geoJson(countries, { // We're taking 'var countries' from countries.js
                style: style,
                onEachFeature: onEachFeature
            }).addTo(map);

            let legend = L.control({position: 'bottomright'});

            legend.onAdd = function (map) {

                let div = L.DomUtil.create('div', 'info legend'),
                    grades = [1, 5, 15, 25, 50, 75, 90],
                    labels = [],
                    from, to;

                for (let i = 0; i < grades.length; i++) {
                    from = grades[i];
                    to = grades[i + 1];

                    labels.push(
                        '<i style="background:' + getColor(from + 1) + '"></i> ' +
                        from + (to ? '&ndash;' + to : '+'));
                }

                div.innerHTML = labels.join('<br>');
                return div;
            };

            legend.addTo(map);
        });


        return (
            <div>
                geolocation
            </div>
        )
    },
    render: function() {
        return(
            <div id="leafletmap" style={{width: "100%", height: "95%", border: "2px solid black" }} />
        )
    }
});

export default Worldmap

基本上现在,例如,如果我想要颜色说俄罗斯,我只需用键值手动添加属性“数据”并将其添加到其中,例如:

{
            "type": "Feature",
            "id": "RUS",
            "properties": {
                "name": "Russia",
                "data": "91"
            },
            "geometry": {
                "type": "MultiPolygon",
                "coordinates": [
                    [
                        [
                            [143.648007, 50.7476],
                        // Coordinates go on .. 

它用&gt;正确地为俄罗斯着色90色: - )

因此,我的问题涉及将dataratio集成到一个完全独立的.js文件中;密钥(例如“RUS”)符合countries.js的结构;但是我如何在这个巨大的countries.js文件中实际添加一个键值存储?

我应该操纵给定countries.js文件中的var countries吗?或者我应该将它集成到我的worldmap.js中,如果是这样,我不知道如何通过匹配另一个js文件中的键来实现。

传单在这种情况下的工作方式是它获取到countries.js并且自身匹配值的键。我是否应该将countries.js变成React类并以这种方式操纵它,但是这是一个庞大的文件并且性能可能令人担忧。

1 个答案:

答案 0 :(得分:0)

我通过以下方式解决了这个问题:

let dataratio = {
            "RUS": "91",
            "NOR": "22",
            "SWE": "91",
            "UKR": "25",
            "GER": "21"
        },

// let dataratio = this.props.data;


let dataratioToArr = Object.keys(dataratio).map(data => [ data, dataratio[data]]); // Conv. map to multidimensional array

let featuresArr = countries.features; // array of all countries in array features from countries.js

for(let i = 0; i < featuresArr.length; i++) // i = 178(no. of countries)
    for(let j = 0; j < dataratioToArr.length; j++) // j = amount of countries we have with dataratio > 1 from backend
        if(dataratioToArr[j][0] == featuresArr[i].id) // If ISO-3 compliant ID of country(f.e. "JPN" or "USA") matches, push a "data" property to countries.js
            featuresArr[i].properties.data = dataratioToArr[j][1];

这基本上会改变内存中的countries.js,只要dataratio不保留值,但如果它不存在则不会被推送。