問題描述
我有下面的反應類,它通過瀏覽器獲取地理位置.
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.
這是反應類:
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.
推薦答案
<div id="leafletmap">
必須添加到dom before 調用 L.map('leafletmap')
.
The <div id="leafletmap">
must be added to the dom before calling L.map('leafletmap')
.
這篇關于傳單:找不到地圖容器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!