Ошибка при попытке сопоставить choropleth с помощью react-leaflet-choropleth: не удается прочитать свойство ‘map’ неопределенного

#javascript #reactjs #leaflet #react-leaflet

#javascript #reactjs #листовка #react-leaflet

Вопрос:

Я пытаюсь создать choropleth при react использовании react-leaflet-choropleth .

У меня листовка работает нормально.
Теперь, когда я пытаюсь загрузить geojson (crimes_by_district) с помощью библиотеки, я получаю сообщение об ошибке при отображении функций, в частности:

 Cannot read property 'map' of undefined
 

Кажется, я неточно ссылаюсь на правильный массив для сопоставления.

Я рассмотрел проблемы в репозитории git и попробовал предложения, но безуспешно. Мне интересно, возможно, я ссылаюсь на неправильные значения из geoJson того, что я использую.

Ниже приведен мой код:

Leaf.js (визуализируется в App.js )

 import React, { Component } from 'react';
import { Map, TileLayer } from 'react-leaflet';
import classes from './leaf.module.css'
import Choropleth from 'react-leaflet-choropleth'
import geojson from "./assets/crimes_by_district.geojson";
    
const style = {
   fillColor: '#F28F3B',
   weight: 2,
   opacity: 1,
   color: 'white',
   dashArray: '3',
   fillOpacity: 0.5
};
    
class Leaf extends Component {
   render() { 
      return (         
         <Map>
           <Choropleth
             data= {{type: 'FeatureCollection', features: geojson.features}}
             valueProperty={(feature) => feature.properties.value}
             // visible={(feature) => feature.id !== active.id}
             scale={['#b3cde0', '#011f4b']}
             steps={7}
             mode='e'
             style={style}
             onEachFeature={
               (feature, layer) => layer.bindPopup(feature.properties.label)
             }
             ref={(el) => this.choropleth = el.leafletElement}
           />
         </Map>
      );
   }
}
    
export default Leaf;
 

Ответ №1:

Создайте свой собственный choropleth wrapper , используя ту же библиотеку choropleth, аналогичную включенному вами расширению, которое react-leaflet-choropleth кажется устаревшим:

 function Choropleth() {
  const { map } = useLeaflet();

  useEffect(() => {
    fetch(
      "https://raw.githubusercontent.com/timwis/leaflet-choropleth/gh-pages/examples/basic/crimes_by_district.geojson"
    )
      .then((response) => response.json())
      .then((geojson) => {
        L.choropleth(geojson, {
          valueProperty: "incidents", // which property in the features to use
          scale: ["white", "red"], // chroma.js scale - include as many as you like
          steps: 5, // number of breaks or steps in range
          mode: "q", // q for quantile, e for equidistant, k for k-means
          style,
          onEachFeature: function (feature, layer) {
            layer.bindPopup(
              "District "  
                feature.properties.dist_num  
                "<br>"  
                feature.properties.incidents.toLocaleString()  
                " incidents"
            );
          }
        }).addTo(map);
      });
  }, []);

  return null;
}
 

а затем импортировать его как дочерний элемент карты:

 <Map center={position} zoom={11} style={{ height: "100vh" }}>
        <TileLayer
          attribution='amp;copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
   <Choropleth />
</Map>
 

вы можете расширить его еще больше, передав различные переменные, которые вам нужны в качестве реквизитов.

ДЕМОНСТРАЦИЯ