小册子:未找到地图容器 [英] Leaflet: Map container not found

查看:1192
本文介绍了小册子:未找到地图容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的react类,可通过浏览器获取地理位置.

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.

这是react类:

    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.

推荐答案

必须在调用L.map('leafletmap')之前将<div id="leafletmap">添加到dom 中.

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

这篇关于小册子:未找到地图容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆