我有以下反应类,它通过浏览器获取地理位置.
我正在绘制传单地图.我想将地理定位作为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容器.加载页面时.环顾四周,通常是因为地图试图在提供值之前显示在div中(在这种情况下为(gelocation,3)).但是,它不应该在从下面的渲染函数返回之前显示它.
问题可能是什么?
在控制台中打印出地理位置正确地获取坐标,这似乎不是问题.
解决方法:
< div id =“leafletmap”>必须在调用L.map(‘leafletmap’)之前添加到dom中.