我有下面的反应类,它通过浏览器获取地理位置。
我正在绘制传单地图。我想将地理定位作为 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.
。环顾四周,通常是因为地图试图在提供值(在本例中为(gelocation,3))之前显示在 div 中。但是,它不应该在从下面的渲染函数返回之前显示它。
可能是什么问题?
在控制台中打印出 geolocation
可以正确获取坐标,因此这似乎不是问题所在。
原文由 cbll 发布,翻译遵循 CC BY-SA 4.0 许可协议
<div id="leafletmap">
必须在调用 之前 添加到 domL.map('leafletmap')
。