我有一个 html 文件 location.html 和一个包含数据 location.data 的文件,它们都位于同一目录中的同一网络服务器上。 location.data 的内容始终是表单中的当前位置数据
{"lat":"44.17027","lon":"15.595542","timestamp":"1723663819127","hdop":"2.394","altitude":"510.35","speed":"0.73396146"}
它是通过另一个 php 文件中的 json_encode() 编写的。 现在我需要将 location.html 中的 JavaScript 数据读取到数组中,以通过传单将其显示在地图上。 (必须是html)
我就是无法完成这件事。我尝试了 XMLHttpRequest() 但没有成功。希望有任何其他(优雅的)方法。
<script>
var locx = new XMLHttpRequest();
locx.open('GET', 'location.data');
locx.onreadystatechange = function () {
if (locx.readyState === 4 && locx.status === 200) {
var locationData = locx.responseText;
}
};
xhr.send();
</script>
如果获取成功,那么其余的将如下所示
// uncomment the commented lines and comment out the const data = {} on your server
//fetch('location.json')
// .then(response => response.json())
// .then(data => {
const data = {"lat":"44.17027","lon":"15.595542","timestamp":"1723663819127","hdop":"2.394","altitude":"510.35","speed":"0.73396146"}
const { lat, lon } = data;
// Initialize the map
const map = L.map('map').setView([lat, lon], 13);
// Add OpenStreetMap tile layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Add a marker to the map at the fetched coordinates
L.marker([lat, lon]).addTo(map)
.bindPopup(`Location: [${lat}, ${lon}]`)
.openPopup();
// })
// .catch(error => console.error('Error fetching the location data:', error));
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<div id="map" style="height: 400px;"></div>