user1521000 user1521000 - 1 year ago 86
PHP Question

Display coordinates from db in Google Maps

So after getting myself informed about how to retrieve x and y coordinates from my database and display them in Google Maps: I went to work. So to make a connection with my mySQL database is wrote this:

$server = '';
$username = 'you';
$password = 'notyou';
$database = 'youapp';
$dsn = "mysql:host=$server;dbname=$database";

(This is all made up)

To retrieve the coordinates from my database and put them in a JSON string I wrote this:

include 'config.php';
try {
$db = new PDO($dsn, $username, $password);
$sth = $db->query("SELECT * FROM youapp");
$youapp = $sth->fetchAll();
echo json_encode( $youapp );
} catch (Exception $e) {
echo $e->getMessage();

I am pretty sure that what I have coded up till now is correct. But I am not sure on the Google Maps part.

<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=""></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++) {
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) {
}"GET", url, true);
<body onload="init();">
<div id="map_canvas" style="width:400px; height: 400px;"></div>

So the function
is a standard Ajax call. But I am not sure how to display the results in Google Maps. If anyone could look at my code to make a connection with my database and give some advice or something on how to display the results from the
in Google Maps, that would be greatly appreciated.

Rob Rob
Answer Source

Everything looks good except you are missing the function displayLocation. Just add this in there:

function displayLocation(item) {
    var marker = new google.maps.Marker({
        // might need to change
        //  to match the column name in your DB
        position: new google.maps.LatLng(, item.lng),
        map: map
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download