javascript - 如何强制传单更新 map ?

标签 javascript reactjs leaflet

我在将 Leaflet 与 React 一起使用时遇到了问题,据我研究,问题是 Leaflet 也想控制 DOM 渲染。

现在,国家将正确地使用与后端信息对应的特定颜色代码(范围 1-->100)进行着色。但是,它每分钟更新一次。更新后,国家颜色不会改变。但是,如果您将鼠标悬停在给定的国家/地区上,它就会出现,这有点奇怪。

这是我的源代码:

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


var Worldmap = React.createClass({

    render: function() {

        if(!this.props.data)
            return <div> loading world map ..  </div>;

        let dataratio = this.props.data; // Props from main component
        let size = Object.keys(dataratio).length; // Do we have data?

        if(size > 1) { // If we do have 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 = no. 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. "USA") matches, push a "data" property to countries.js
                        featuresArr[i].properties.data = dataratioToArr[j][1];
        }

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

    componentDidMount : function() {
        let geolocation =  [];
        // Retrieve geoloc coordinates
        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); // ([coordinates], zoomlevel)

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

            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, { // from import
                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);
        });

    }
});

export default Worldmap

如何在接收到新的 this.props.data 时强制传单重绘或刷新 map ?

我尝试使用 componentDidUpdate,我基本上会做 map.remove(),但后来我遇到了不同组件之间的范围问题。它全部加载到 componentDidMount 如果你再次调用传单 map ,它会说它已经初始化了。

最佳答案

扩展我的评论。 您需要清除图层并将数据重新添加到您的 map 。在您的情况下,您可能需要更改访问 map 和 geojson 处理的方式,但我在这里为您提供一般解决方案。

   componentDidMount(){
      var map = this.map = L.map('leafletmap');
   } 


   componentWillReceiveProps(nextProps) {
      if (nextProps.data !== this.props.data) {
       this.map.clearLayers();
      }
   } 


  componentDidUpdate(prevProps,prevState) {
      if (prevProps.data !== this.props.data) {
          this.map.addData(geojsonData);
       }
   }

关于javascript - 如何强制传单更新 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42926234/

相关文章:

reactjs - 如何修复导入错误 "Module not found: Can' t 解析 './components'“- 使用命名导出

javascript - CasperJS 后退导航不起作用

php - 使用 CakePHP 3.x 设置 ReactJS 的最佳方法是什么?

javascript - Koa 将数据从服务器传递到客户端

javascript - 正确使用 onCompleted 进行 GraphQL 突变

javascript - 使用传单将边界图层添加到离线 map

javascript - 无法让 load() 在 img 上工作

javascript - 以下元素的 Vue 2 切换类

javascript - 关于Chrome扩展程序的存储权限

twitter-bootstrap-3 - 模态中的传单和 Mapbox 无法正确显示