传单:找不到地图容器

2022-01-12 00:00:00 reactjs leaflet javascript react-leaflet

我有下面的反应类,它通过浏览器获取地理位置.

I have the below react class which fetches the geolocation through the browser.

我正在绘制一张传单地图.我想将地理位置作为 setView 的输入,以便地图缩放"到客户端浏览器位置的区域.

I am mapping a leaflet map. I want to geolocation to be an input to the setView, for such that the map "zooms" into the region of the client browser location.

这是反应类:

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

    var Worldmap = React.createClass({

        render: function() {

            let geolocation = [];

            navigator.geolocation.getCurrentPosition(function(position) {
                let lat = position.coords.latitude;
                let lon = position.coords.longitude;
                geolocation.push(lat, lon);
                locationCode()
            });

            function locationCode() {
                if(geolocation.length <= 0)
                    geolocation.push(0, 0);
            }


            let map = L.map('leafletmap').setView(geolocation, 3);

            L.geoJSON(countries, {
                style: function(feature) {
                    return {
                        fillColor: "#FFBB78",
                        fillOpacity: 0.6,
                        stroke: true,
                        color: "black",
                        weight: 2
                    };
                }
            }).bindPopup(function(layer) {
                return layer.feature.properties.name;
            }).addTo(map);

            return (
                <div id="leafletmap" style={{width: "100%", height: "800px" }}/>
            )
        }
    });

    export default Worldmap

在 HTML 呈现为 <WorldMap/> 的主文件中调用它.

It's called in a main file where the HTML is rendered as <WorldMap />.

我在加载页面时收到错误 Uncaught Error: Map container not found..环顾四周,通常是因为地图在提供值之前试图在 div 中显示(在这种情况下为 (gelocation, 3)).但是,它不应该在从下面的渲染函数返回之前显示它.

I get the error Uncaught Error: Map container not found. when loading the page. Looking around, usually it would be because the map is trying to be displayed in a div before being provided values((gelocation, 3) in this case). However, it shouldn't display it before being returned from the render function below.

可能是什么问题?

在控制台中打印出 geolocation 可以正确获取坐标,因此这似乎不是问题.

Printing out the geolocation in the console correctly fetches the coordinates, so that doesn't seem to be the issue.

推荐答案

<div id="leafletmap"> 必须添加到dom before 调用 L.map('leafletmap').

The <div id="leafletmap"> must be added to the dom before calling L.map('leafletmap').

相关文章