反应传单地图未正确显示

时间:2016-11-01 17:33:01

标签: javascript reactjs react-leaflet

我尝试使用react-leaflet来显示地图。我使用this fiddle中的代码正常工作,但在我的计算机上我有这个输出

enter image description here

这是我的代码:

DeviceMap.js

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

export class DeviceMap extends React.Component {
  constructor() {
    super();
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13,
    };
  }

  render() {
    const position = [this.state.lat, this.state.lng];
    return (
      <Map center={position} zoom={this.state.zoom} scrollWheelZoom={false}>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        <Marker position={position}>
          <Popup>
            <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
          </Popup>
        </Marker>
      </Map>
    );
  }
}

export default DeviceMap

DeviceTabs.js

export class DeviceTabs extends React.Component {
  state = {
    index: 0
  };

  handleTabChange = (index) => {
    this.setState({ index })
  };

  render () {
    return (
      <Tabs index={this.state.index} onChange={this.handleTabChange}>
        <Tab label='Values'>
          <DeviceTable {...this.props} />
        </Tab>
        <Tab label='Map'>
          <div className={style.leaflet}>
            <DeviceMap />
          </div>
        </Tab>
      </Tabs>
    )
  }
}

style.scss

.leaflet {
  height: 300px;
  width: 100%;
}

控制台中没有错误,我不知道在哪里搜索。由于小提琴正在运作,它不是一个错误。我错过了什么吗?

16 个答案:

答案 0 :(得分:18)

看起来您尚未加载Leaflet样式表。

来自react-leaflet github指南:

  

如果您不熟悉Leaflet,请确保在使用此库之前阅读其快速入门指南。   您需要将其CSS添加到页面中以正确渲染地图,并设置容器的高度。

http://leafletjs.com/examples/quick-start/

以下是您需要的内容:

DensityPlot[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}, 
 PlotRangePadding -> 0.2, GridLines -> Automatic, 
 Method -> {"GridLinesInFront" -> True}]

它的价值,文档页面设计不佳 ...并且维护者在github中不断处理这个问题,但由于某种原因,问题是用户的错误谁不断进行必要的设置。

答案 1 :(得分:10)

我对使用这个库还是陌生的,并且没有找到足够清晰的文档。但是,为了使它正常工作,我发现有一些必要的东西。

1。 react-leaflet程序包

2。单张包:

要么使用npm进行安装

npm install leaflet
import 'leaflet/dist/leaflet.css';Map中使用react-leaf的文件中。

OR

index.html中包括这两行:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
  integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
  crossorigin=""/>

<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
  integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
  crossorigin=""></script>

3。将此添加到App.css或index.css并导入文件:(及其必需)

.leaflet-container {
  width: 100wh; 
  height: 100vh;
}

//或直接向地图容器添加样式

<Map
   center={position}
   zoom={1}
   style={{ height: '100vh', width: '100vh' }}
   >
   <TileLayer .... />
</Map>

答案 2 :(得分:5)

您可以通过在index.html的head元素内添加以下代码行来进行修复。

throw 'allowScriptTagRemoting is false.';
//#DWR-INSERT
//#DWR-REPLY
var s0={};
dwr.engine._remoteHandleCallback('1','0',{application:"bdsa",changedParts:null,currentRow:-1,dialogLevel:0,dialogTitle:null,error:null,focusPropertyId:null,forwardInNewWindow:false,forwardURL:null,forwardURLs:null,hideDialog:false,module:"SignIn",nextModule:null,propertiesUsedInCalculations:null,reload:true,resizeDialog:false,selectedRows:null,showDialog:false,strokeActions:s0,urlParam:null,viewMember:"",viewSimple:false});

注意:您可以更改CSS以满足您的需求。

答案 3 :(得分:3)

如果有人正在寻找如何将其嵌入到一个单独的组件中,经过一番挣扎,我想出了如何做到这一点

import React from 'react';
import { MapContainer, Marker, Popup, TileLayer } from "react-leaflet";
import './MapObject.css'

const position = [51.505, -0.09]
class MapObject extends React.Component {
    render() {

        return (
                <MapContainer center={position} zoom={13} scrollWheelZoom={false}>
                <TileLayer
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <Marker position={position}>
                <Popup>
                    A pretty CSS3 popup. <br /> Easily customizable.
                </Popup>
                </Marker>
            </MapContainer>           
        );
    }
}

这是然后简单地加载

import MapObject from './MapObject'

MapObject.css 需要看起来像这样(没有这个它根本不会出现)

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

结果地图在这里:

enter image description here

答案 4 :(得分:2)

导入leaflet.css

import 'leaflet/dist/leaflet.css';

有时,添加传单文件后,有关图像加载的两个错误。为了解决这些错误,请在导入部分中导入marker-icon.png和marker-shadow.png,然后定义L.Marker.prototype.options.icon:

import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';
let DefaultIcon = L.icon({
            iconUrl: icon,
            shadowUrl: iconShadow
        });
        L.Marker.prototype.options.icon = DefaultIcon;

如果未显示地图,则将高度和宽度(样式= {{width:'100%',height:'400px'}})添加为Map标签的样式:

<Map
center={[35.6892, 51.3890]}
style={{width: '100%',height: '400px'}}
>

enter link description here

答案 5 :(得分:1)

这解决了我的问题:

将此添加到index.html

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css">

<style>
  .leaflet-container {
   height: 400px;
   width: 800px;
 }
</style>

来源:https://medium.com/@eugenebelkovich/map-for-react-apps-with-leaflet-365f9df82d55

答案 6 :(得分:1)

以我为例,React添加了此帮助:

<MapContainer
        center={{ lat: 51.505, lng: -0.09 }}
        zoom={13}
        style={{ height: "50vh", width: "100%" }}
        scrollWheelZoom={false}
      >

vh 必须至少为1个参数的高度或宽度,否则,如果仅使用100%/ 100%,则无效

答案 7 :(得分:1)

你应该把它添加到你的 CSS 文件中,我和你有同样的问题,这个方法解决了我的问题:

  @import url("~leaflet/dist/leaflet.css");

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

答案 8 :(得分:0)

**Go to your react app folder my-app/public/index.html open index.html

and pest this two links in head tag
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"></script>

</head>**



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css">
    <style>
    #mpp {

            overflow: hidden;
        }
    </style>
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

答案 9 :(得分:0)

以防万一有人遇到相同的问题,我只需添加以下内容即可解决:

import 'leaflet/dist/leaflet.css';

答案 10 :(得分:0)

尝试一下

import React, { Component } from 'react'
import Leaflet from 'leaflet';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet'
import 'leaflet/dist/leaflet.css';

Leaflet.Icon.Default.imagePath =
'../node_modules/leaflet'

delete Leaflet.Icon.Default.prototype._getIconUrl;

Leaflet.Icon.Default.mergeOptions({
    iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
    iconUrl: require('leaflet/dist/images/marker-icon.png'),
    shadowUrl: require('leaflet/dist/images/marker-shadow.png')
});



export default class MapDisplay extends Component {
state = {
    lat: 41.257017,
    lng: 29.077524,
    zoom: 13,
}


render() {
    const position = [this.state.lat, this.state.lng]
    return (
    <Map center={position} zoom={this.state.zoom} style={{height : '400px'}}>
        <TileLayer
        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={position}>
        <Popup>
            Son Konum
        </Popup>
        </Marker>
    </Map>
    )
}
}

答案 11 :(得分:0)

尝试:

 var mapid = $(this).find('[id^=leaflet-map]').attr('id');
      var map = settings.leaflet[mapid].lMap;
      map.invalidateSize();

答案 12 :(得分:0)

在Leaflet Map中,如果您的地图显示不正确,则此问题是由于CSS文件引起的。

在您的public / index.html中试用此CSS

<link href='https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.css' rel='stylesheet'>

答案 13 :(得分:0)

如果这些都不适合您,则可以尝试在页面加载时手动调整窗口大小。

window.dispatchEvent(new Event('resize'));

答案 14 :(得分:0)

即使设置了高度和css,我的地图也完全没有显示。 您需要将以下传单cdn和css添加到index.html文件中,以使其起作用:

<link rel="stylesheet" 
href="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css">    
<style>
     .leaflet-container {
       height: 500px;
       width: 960px;
     }    </style>

    <!-- Make sure you put this AFTER Leaflet's CSS -->
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
      integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
      crossorigin=""></script>
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

答案 15 :(得分:0)

不知道为什么,添加 Leaflet css 文件还不够...

看来您还必须添加:

.leaflet-container{
  height:500px;
}
相关问题