我正在尝试将标记添加到谷歌地图中,并从mysql数据库中查询坐标。脚本如下所示,位于名为connection.php的文件中。
$query = "SELECT site, latitude, longitude, pollution FROM pollution_monitoring.locations";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$site = $row['site'];
$latitude = $row['latitude'];
$longitude = $row['longitude'];
$pollution = $row['pollution'];
echo ("addMarker($latitude,$longitude,'<b>$site</b><br/>$pollution');\n");
}
addMarker()是一个已在下面的文件中定义的JavaScript函数
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
google.maps.event.addDomListener(window, 'load', initialize);
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 500
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initialize() {
var mapProp = {
center: new google.maps.LatLng(-29.335989, 27.483622999999966),
zoom: 17,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
zoomControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
$.get('connection.php');
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addDomListener(window, 'load', initialize);
以上脚本用于加载Google地图,并且必须将标记添加到地图中。我原以为php脚本(addMarker函数)的结果会被运行并将标记添加到地图中,但这不会发生。然后将JavaScript包含在jsp文件中。地图会加载,但不会添加任何标记。
我做错了什么?
答案 0 :(得分:0)
您应该重写您的php脚本以生成JSON数据:
header('Content-Type: application/json');
$query = "SELECT site,latitude,longitude,pollution FROM pollution_monitoring.locations";
$result = mysqli_query($conn,$query);
$i = 0;
echo '[';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
if ($i++ != 0) echo ',';
echo json_encode($row);
}
echo ']';
然后使用JavaScript添加标记:
$.getJSON('connection.php', function(data) {
for (var i = 0; i < data[i]; i++) {
addMarker(data[i].latitude, data[i].longitude, "<b>" + data[i].site + "</b><br />" + data[i].pollution);
}
});