我已经尝试了几乎所有东西,但我无法更正我的代码。我的代码没有显示谷歌地图和标记。我有一个sqlite3 db canberra.db,我从中获取数据。
canberra.db:
CREATE TABLE `markers` (
`city_id` INTEGER,
`name` TEXT,
`latitude` TEXT,
`longitude` TEXT,
`type` TEXT
)
提前感谢任何帮助。
test.php的:
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('canberra.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql=<<<EOF
SELECT * from markers;
EOF;
$result = $db->query($sql);
$json = array();
while($row = $result->fetchArray(SQLITE3_ASSOC) ){
echo $json[]['lat'] = $row['latitude'];
echo $json[]['lon'] = $row['longitude'];
echo $json[]['name'] = $row['name'];
echo $json[]['type'] = $row['type'];
}
$db->close();
echo "Operation done successfully\n";
?>
<script type="text/javascript">
function initMap() {
var locationsJSON = '<?php echo json_encode($json) ?>';
var locations = JSON.parse(locationsJSON);
var bounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
for (i = 0; i < locations.length; i++) {
console.log(locations[i]);
var myLatLng = new google.maps.LatLng(locations[i].lat, locations[i].lon);
bounds.extend(myLatLng);
map.fitBounds(bounds);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDooxT39owZBkpRXCGKPbRuQd5fSkr0Xvk&callback=initMap">
</script>
答案 0 :(得分:1)
尝试var_dumping你的$ json数组,你就会发现错误。
您可以使用以下内容替换while循环内容:
$json[] = array(
'lat' => $row['latitude'],
'lon' => $row['longitude'],
'name' => $row['name']
);
答案 1 :(得分:1)
我已更改此功能,我的代码可以正常工作:)
function initMap() {
debugger;
var locationsJSON = <?php echo json_encode($json, JSON_PRETTY_PRINT) ?>;
var locations = locationsJSON;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
for (i = 0; i < locations.length; i++) {
console.log(locations[i]);
var myLatLng = new google.maps.LatLng(locations[i].lat, locations[i].lon);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
}
还有一件事我也在顶部发布了php脚本。
<?php
class MyDB extends SQLite3
?>
<!DOCTYPE html>
<html>
</html>
我希望这会有所帮助。
答案 2 :(得分:0)
使用
创建数组echo $json[]['lat'] = $row['latitude'];
echo $json[]['lon'] = $row['longitude'];
echo $json[]['name'] = $row['name'];
但是你要指的是坐标:
var myLatLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
将其更改为:
var myLatLng = new google.maps.LatLng(locations[i].lat, locations[i].lon);