React-leaflet 渲染不正常

17

react-leaflet地图无法正确渲染。

  • 地图渲染在其父元素范围之外
  • 地图的某些瓦片缺失

当与标准的react组件一起使用地图时,会出现此问题。

我的网站还使用了react-bootstrap。据我所读,这可能会导致react-leaflet的渲染出现一些潜在问题。

import React from 'react';
import ReactDOM from 'react-dom';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';

const position = [37.335556, -122.009167];

class MapView extends React.Component {
    render() {
        return (
                  <div
                    style={{
                        height:"100%"
                    }}>
                    <Map center={position} zoom={13}>
                        <TileLayer
                          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        />
                        <Marker position={position}>
                          <Popup>
                            <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                          </Popup>
                        </Marker>
                      </Map>
                  </div>
        );
    }
}

module.exports = MapView;

这会被渲染

4个回答

23

首先,在控制台中安装:

> npm install leaflet 
> npm install react-leaflet

在 index.js 中导入一个位于 node_modules 中的 CSS。

//src/index.js
    import 'leaflet/dist/leaflet.css'

那么现在只需加上一个边距和高度:

    ////src/App.js 
return (
            <MapContainer center={position} zoom={3} scrollWheelZoom={false} 
        style={{ height:"`enter code here`400px",backgroundColor:"red",marginTop:"80px", marginBottom:'90px'
            }} >
        </MapContainer>
        )
或者
   return (
        <>
          <Map style={{ width: "100%", height: "100vh" }} center={center} zoom={13}>
            </Map>
</> )

1
这比leaflet的文档好太多了。谢谢。 - TTS
我百分之百同意@TTS的观点,绝对比原始文档好得多。非常感谢! - ardabzlk

10

还要将这些Leaflet的CSS和JS文件添加到您的项目中

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>

还需要在地图上添加高度信息,这是必须的。

这是一个简单的JsFiddle例子。另外,请查看外部资源。


7
主要问题是CSS未被导入,并且Map组件的高度未设置。
我通过使用react-leaflet-marker-layer解决了缺少标记图像的问题。
import React from 'react';
import ReactDOM from 'react-dom';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import MarkerLayer from 'react-leaflet-marker-layer';

const position = { lng: -122.673447, lat: 45.522558 };
const markers = [
  {
    position: { lng: -122.67344700000, lat: 45.522558100000 },
    text: 'Voodoo Doughnut',
  },
  {
    position: { lng: -122.67814460000, lat: 45.5225512000000 },
    text: 'Bailey\'s Taproom',
  },
  {
    position: { lng: -122.67535700000002, lat: 45.5192743000000 },
    text: 'Barista'
  },
  {
    position: { lng: -122.65596570000001, lat: 45.5199148000001 },
    text: 'Base Camp Brewing'
  }
];

class ExampleMarkerComponent extends React.Component {

  render() {
    const style = {
      border: 'solid 1px lightblue',
      backgroundColor: '#333333',
      borderRadius: '50%',
      marginTop: '-5px',
      marginLeft: '-5px',
      width: '10px',
      height: '10px'
    };

    return (
      <div style={Object.assign({}, this.props.style, style)}></div>
    );
  }

}

class MapView extends React.Component {
    render() {
        return (
                  <div
                    style={{
                        height:"700px"
                    }}>
                    <Map center={position} zoom={13}
                        style={{
                            height:"700px"
                        }}>
                        <TileLayer
                          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        />
                        <MarkerLayer
                            markers={markers}
                            longitudeExtractor={m => m.position.lng}
                            latitudeExtractor={m => m.position.lat}
                            markerComponent={ExampleMarkerComponent} />
                      </Map>
                  </div>
        );
    }
}

module.exports = MapView;

0
也许你可以尝试这个,它适用于React.js或Next.js,目前在react.js 18上运行良好。
首先,我建议卸载任何leaflet库,然后安装这个。
npm i leaflet leaflet-defaulticon-compatibility leaflet-geosearch 

你可以使用这段代码:
import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react'


const markerRef = useRef(null)
const eventHandlers = useMemo(
        () => ({
            dragend() {
                const marker = markerRef.current
                if (marker != null) {
                    // setPosition(marker.getLatLng())
                    console.log(marker.getLatLng())
                }
            },
        }),
        [],
    )
    useEffect(() => {
     // you will get the current position of the marker here
        console.log(markerRef.current)
    }, [markerRef.current])

//////////////////////
/// in the html

<MapContainer center={[40.8054, -74.0241]} zoom={14} scrollWheelZoom={false} style={{ height: "400px", width: "100%" }}>
    <TileLayer
    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
        <Marker
            eventHandlers={eventHandlers}
            position={[40.8054, -74.0241]}
            draggable={true}
            animate={true}
            ref={markerRef}
        >
       <Popup>
           Hey ! you found me
       </Popup>
   </Marker>
</MapContainer>

这里复制


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接