У меня есть приведенный ниже класс реакции, который извлекает геолокацию через браузер.
Я составляю карту листовки. Я хочу, чтобы геолокация использовалась в качестве входных данных для setView, чтобы карта «приближалась» к области расположения клиентского браузера.
Вот класс реакции:
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 />
.
Я получаю ошибку Uncaught Error: Map container not found.
при загрузке страницы. Если оглянуться вокруг, обычно это происходит из-за того, что карта пытается отобразить в div до того, как ей будут предоставлены значения (в данном случае (gelocation, 3)). Однако он не должен отображать его до возврата из функции рендеринга ниже.
В чем может быть проблема?
Распечатка geolocation
в консоли правильно определяет координаты, так что, похоже, это не проблема.