所以在让我自己了解如何从我的数据库中检索x和y坐标并在Google地图中显示它们之后:我去了工作。因此,为了与我的mySQL数据库建立连接,请写下:
<?php
$server = '132.3.2.1.';
$username = 'you';
$password = 'notyou';
$database = 'youapp';
$dsn = "mysql:host=$server;dbname=$database";
(This is all made up)
要从我的数据库中检索坐标并将它们放在JSON字符串中,我写了这个:
<?php
include 'config.php';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth = $db->query("SELECT * FROM youapp");
$youapp = $sth->fetchAll();
echo json_encode( $youapp );
} catch (Exception $e) {
echo $e->getMessage();
}
我很确定到目前为止编码的内容是正确的。但我不确定谷歌地图部分。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Beer Me</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
var map;
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
makeRequest('get_locations.php', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
// IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
// IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body onload="init();">
<div id="map_canvas" style="width:400px; height: 400px;"></div>
</body>
</html>
因此函数makerequest
是标准的Ajax调用。但我不确定如何在Google地图中显示结果。如果有人可以查看我的代码以建立与我的数据库的连接,并提供一些建议或者如何在Google地图中显示makerequest
的结果,那将非常感激。
答案 0 :(得分:2)
除了缺少函数displayLocation
之外,一切看起来都不错。只需在此处添加:
function displayLocation(item) {
var marker = new google.maps.Marker({
// might need to change item.lat/item.lng
// to match the column name in your DB
position: new google.maps.LatLng(item.lat, item.lng),
map: map
});
}
答案 1 :(得分:0)
尝试这个。
function displayLocation(item) {
var marker = new google.maps.Marker({
// might need to change item.lat/item.lng
// to match the column name in your DB
position: new google.maps.LatLng(item.lat, item.lng),
map: map
});
}