user1521000 user1521000 - 2 months ago 14
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:

<?php
$server = '132.3.2.1.';
$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:

<?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();
}


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

<!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>


So the function
makerequest
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
makerequest
in Google Maps, that would be greatly appreciated.

Rob Rob
Answer

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 item.lat/item.lng
        //  to match the column name in your DB
        position: new google.maps.LatLng(item.lat, item.lng),
        map: map
    });
}