已解决 - 请参阅下面的答案
我有一个名为“locationLogs”的 MySql 数据库和一个名为“locations”的表。我有一个名为 map.php 的页面,它显示地图(使用 Mapbox GLJS API)。然后,我想为“位置”表中的每个位置添加一个标记。该表由“id”、“经度”和“纬度”组成。然后我使用 while 循环来尝试这个。然而,当进入该页面时,它只显示空白,并且不加载地图或任何内容。我的页面代码如下。
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Live Map</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v2.9.2/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v2.9.2/mapbox-gl.css' rel='stylesheet' />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.marker {
background-image: url('mapbox-icon.png');
background-size: cover;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'MY_ACCESS_TOKEN';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-96, 37.8],
zoom: 3
});
// code from the next step will go here!
<?php
$conn = mysql_connect("localhost", "DB_USER", "DB_PASS");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("locationLogs")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT *
FROM locations";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
?>
const geojson = {
type: 'FeatureCollection',
features: [
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '
{
type: "Feature",
geometry: {
type: "Point",
coordintes: [' . $row['longitude'] . ', ' . $row['latitude'] . ']
},
properties {
title: "Location",
description: "A cool location",
}
},';
}
mysql_free_result($result);
?>
]
};
// add markers to map
for (const feature of geojson.features) {
// create a HTML element for each feature
const el = document.createElement('div');
el.className = 'marker';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el).setLngLat(feature.geometry.coordinates).addTo(map);
}
</script>
</body>
</html> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我必须重新编写很多代码才能使其正常工作。我将在下面附上完整的代码文件。数据库结构为:
表:位置
id 经度纬度 显示名称 显示描述
?>Live Map
connect_errno ) {
printf("Connect failed: %s", $mysqli->connect_error); exit(); } printf('Connected successfully.
'); $sql = "SELECT * FROM location"; $result = $mysqli->query($sql); if ($result->num_rows > 0) { } else { printf('Unexpected Error. DB did not return enough values for a successful export.
'); } ?>