Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

javascript - Leaflet: Map container not found

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

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.

Here's the react class:

    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

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

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.

What could the issue be?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...