简体   繁体   English

为什么传单地图不会在反应应用程序上呈现

[英]why leaflet map doesn't render on react app

I included leaflet map with js implementation instead of jsx implementation but I have a problem as it overflows its scope.我在js实现中包含了传单地图,而不是jsx实现,但是我遇到了一个问题,因为它超出了它的范围。

this is how I imported leaflet:这是我导入传单的方式:

import L from 'leaflet';

and implemented:并实施:

componentDidMount() {
    // create map
    this.map = L.map('map', {
      center: [49.8419, 24.0315],
      zoom: 16,
      layers: [
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
          attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        }),
      ]
    });
  }

and usage:和用法:

<div id={"map"} > 

and this is what i got这就是我得到的在此处输入图片说明

You have not added the leaflet css file in your index.html .您尚未在index.html添加传单 css 文件。

For leaflet version 1.3.4 , add the following to index.html对于传单版本1.3.4 ,将以下内容添加到 index.html

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css"
   integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
   crossorigin=""/>  

In your map component css file, override the leaflet-container class with desired height and width.在您的地图组件 css 文件中,使用所需的高度和宽度覆盖leaflet-container类。

.leaflet-container {
  height: 600px;
  width: 100%;
}

Once you have added that, use Map and TileLayer Components of react-leaflet to render map.添加后,使用react-leaflet MapTileLayer组件来渲染地图。

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Map, TileLayer } from "react-leaflet";
import "./styles.css";

class App extends Component {
  state = {
    center: [51.505, -0.091],
    zoom: 13
  };

  render() {
    return (
      <div>
        <Map center={this.state.center} zoom={this.state.zoom}>
          <TileLayer
            attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
          />
        </Map>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);  

You can find working code here.您可以在此处找到工作代码。 https://codesandbox.io/s/2wnv7o1mlr https://codesandbox.io/s/2wnv7o1mlr

Yeah you're missing the css file.是的,您缺少 css 文件。

incidentally this is not how you should be using react-leaflet .顺便说一句,这不是您应该如何使用react-leaflet componentDidMount is not the place for doing what you're doing. componentDidMount 不是做你正在做的事情的地方。 Put that in the render like把它放在渲染中

import { Map, TileLayer } from 'react-leaflet'; 
<Map>
      <TileLayer url="'http://{s}.tile.osm.org/{z}/{x}/{y}.png'" />
</Map>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM