I'm just learning how to use the google maps with info from my database, and i'm having some trouble. I can get the map to appear with no problem, and the info from my database is being pulled correctly in the php page, but i can't seem to call that information in my html page. I'm trying to get little icons to appear on the map at each location in the database, but so far, nothing is appearing other than the google maps box. Any help would be greatly appreciated!
googleMap.php
<?
$username="myUsername";
$password="myPassword";
$database="myDatabase";
?>
<?php
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Start XML file, echo parent node
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo 'marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
?>
googleMap.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl(googleMap.php, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
/body>
</html>
IN your PHP file you're echoing every row. But the markup is not correct. It should be a proper xml-node, you're displaying just some text.
header("Content-type: text/xml");
// Start XML file, create parent node
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("markers");
$parnode = $doc->append_child($node);
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $doc->create_element("marker");
$newnode = $parnode->append_child($node);
$newnode->set_attribute("name", $row['name']);
$newnode->set_attribute("address", $row['address']);
$newnode->set_attribute("lat", $row['lat']);
$newnode->set_attribute("lng", $row['lng']);
$newnode->set_attribute("type", $row['type']);
}
See this link: https://developers.google.com/maps/articles/phpsqlajax_v3#outputxml
Related
I am gathering live data from a mysql database using php and ajax. I want the data to be live updated every 2 seconds.
My code displays the chart and data as I want it, but does not live update the data from the database. The piece of code meant to be doing that is:
setInterval(function(){
jsonData.ajax.reload();
}, 2000);
And I think the error lies somewhere there as when I inspect the element with google chrome it tells me "Uncaught TypeError: Cannot read property 'reload' of undefined".
Here is the full JS code:
<script type="text/javascript">
// load chart lib
google.load('visualization', '1', {
packages: ['corechart']
});
// call drawChart once google charts is loaded
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "php/connection3_temp.php",
dataType:"json",
async: true
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Ambient Temp.');
data.addColumn('number', 'Object Temp.');
data.addColumn('number', 'Humidity');
$.each(results, function (i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.amb_temp),
parseFloat(row.obj_temp),
parseFloat(row.hum)
]);
});
var options = {
title: 'Temperature and Humidity against Time',
legend: { position: 'bottom' },
series: {
0: {targetAxisIndex: 0},
1: {targetAxisIndex: 0},
2: {targetAxisIndex: 1}
},
vAxes: {0: {title: 'Temp. (°C)',
minValue: 0,
maxValue: 30
},
1: {title: 'Humidity (%)',
minValue: 20,
maxValue: 80
}
},
hAxis: {
title: 'Time (s)'
},
};
var chart = new google.visualization.LineChart($('#temp_chart').get(0));
chart.draw(data, options);
});
setInterval(function(){
jsonData.ajax.reload();
}, 2000);
}
</script>
and also the PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "raspberryblue";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM sensortag3 ORDER BY id DESC LIMIT 3000";
$result = $conn->query($sql);
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysqli_error() . "<br>";
$message .= 'Whole query: ' . $sql;
die( $message );
}
// Print out rows
$prefix = '';
echo "[\n";
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "timestamp": "' . $row['timestamp'] . '",' . "\n";
echo ' "amb_temp": "' . $row['amb_temp'] . '",' . "\n";
echo ' "obj_temp": "' . $row['obj_temp'] . '",' . "\n";
echo ' "hum": "' . $row['hum'] . '"' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
$conn->close();
?>
There's no property named reload() in your script. That's why the console is showing undefined property reload(). So add the reload method inside ajax() for refreshing the data.
I'm trying to produce a map with multiple markers using XML values which are produced using a PHP file I have written. I can successfully print out XML values from my PostGreSQL database onto a 'markers.php' page.
However, when I try and load the data into a Google Maps map the map itself doesn't show or any of the markers. The canvas in which the map is placed doesn't appear either.
Could anyone identify a problem with my script? The PHP side of things work perfectly I'm just looking for a solution which will load the map and the multiple markers with lat/lng values taken from the database. Please see the relevant files below.
Markers.php
session_start();
$username = $_SESSION['nickname'];
function parseToXml($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
$conn = pg_connect("dbconnectionstring");
if(!conn){
die ("Not connected : " . pg_last_error());
}
/*USE $username VARIABLE TO GET THE U_ID WHICH CORRESPONDS TO THE OWNER COLUMN IN RECORDS*/
$sql = "SELECT * FROM users WHERE username='$username'";
$sqlres = pg_query($sql);
$sqlassoc = pg_fetch_assoc($sqlres);
$owner = $sqlassoc['u_id'];
$query = "SELECT * FROM records WHERE owner='$owner'";
$result = pg_query($query);
if(!$result){
die('Invalid query : ' . pg_last_error());
}
header("Content-type: text/xml");
echo '<markers>';
while($row = pg_fetch_assoc($result)){
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'description="' . parseToXML($row['description']) . '" ';
echo 'latitude="' .parseToXML($row['latitude']) . '" ';
echo 'longitude="' .parseToXML($row['longitude']) . '" ';
echo 'project="' .parseToXML($row['project']) . '" ';
echo '/>';
}
echo '</markers>';
This script works perfectly and produces the XML appropriately.
Map.php - which contains the javascript
function load(){
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(51.4129, -4.0774),
zoom: 13,
mayTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow;
/*markers.php file in same directory as map.php*/
downloadUrl("markers.php", function(data){
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++){
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("description");
var project = markers[i].getAttribute("project");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var html = "<b>" + name + "</b> <br />" + "<b>" + description + "</b> <br />" + project;
var iconBase = 'http://users.aber.ac.uk/dwd/mfb/images';
var marker = new google.maps.Marker({
map: map,
position: point,
icon: iconBase + 'map_icon.png'
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadstatechange = function() {
if(request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
This code is taken from the Google Maps with PHP/MySQL tutorial and yet I can't see to get it to work. Any ideas?
Is there an equivalent to the following:
header("Content-type: text/xml");
I'm using Google Maps with Wordpress and I get the "headers already sent" error. I've gone through all the files and taken out all the whitespace but the error still appears so just wondering if there was another way of doing the code above.
This is the error:
Warning: Cannot modify header information - headers already sent by (output started at /home/medicom/public_html/mapping/wp-content/themes/default/header.php:11) in /home/medicom/public_html/mapping/wp-content/themes/default/new-version1.php on line 45
And this is my page - http://www.mediwales.com/mapping/test/
<?php
/**
* #package WordPress
* #subpackage Default_Theme
* Template Name: Latest Version
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type');?>; charset=<?php bloginfo('charset');?>" />
<title><?php wp_title('«', true, 'right');?></title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url');?>" type="text/css" media="screen" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="<?php bloginfo('template_directory'); ?>/markerclusterer.js" type="text/javascript"></script>
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAdnbfsmnsdaFBmEZfsJEmiWC7p0LLmMBSsffI9l26I_viUYjW7vRG7TlO-sRQKR0B_YAsP2VnDdVgsr4Aegvksdw" type="text/javascript"></script>
<?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); ?>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?> onload="load()" onunload="GUnload()">
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div id="body">
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
<script type="text/javascript">
//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconRed.iconSize = new GSize(12, 20);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["restaurant"] = iconBlue;
customIcons["bar"] = iconRed;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 13);
GDownloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name, address, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
</script>
<div id="map" style="width: 500px; height: 300px"></div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
<?php wp_footer(); ?>
</body></html>
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.
No. You can't send headers after they were sent. Try to use hooks in wordpress
I'm trying to have multiple values for profFName and profLName display on a map where a single point should display this value.
So, if I have (2) pID connected to the same marker... it should display the profFName and profLName on one point.
** Right now it is creating two markers at the exact same lat/longitude so it is plotting 3 points (as seen from the database) but it doesnt show (1) point if multiple professors exist at that location **
Javascript
<script type="text/javascript">
//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconRed.iconSize = new GSize(12, 20);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["restaurant"] = iconBlue;
customIcons["bar"] = iconRed;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 13);
GDownloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var profFName = markers[i].getAttribute("profFName");
var profLName = markers[i].getAttribute("profLName");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, profFName, profLName, type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name, address, profFName, profLName, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address + "<br><br>" + profFName + profLName;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 110 0px; height: 500px"></div>
</body>
PHP
<?php
require("phpsqlajax_dbinfo.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect ($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers M, professor P
WHERE P.id = M.id;";
if($row = mysql_fetch_array($result)) {
do {
echo $row;
}
while($row = mysql_fetch_array($result));
} else {
die('No results.');
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'profFName="' . parseToXML($row['profFName']) . '" ';
echo 'profLName="' . parseToXML($row['profLName']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
Quick solutions:
Use GROUP_CONCAT function
Can I concatenate multiple MySQL rows into one field?
display only markers and add attribute id to each marker. When you click on marker
select from database and concat received rows
Create associative array of added markers {id: marker reference}. In function createMarker
check this array and if marker id is already present, concate html of marker in array with
marker passed in function. If not add marker to array.
I am using the Google Maps API with parts in javascript and others in PHP.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAA3fq9XBWvtS9ZYB0aG-cTRTkZyK8gYtfVqvwV6-79vPRam6nLBTe_uKtAZgMBEjBkeS1dJQ6LKQ1Cw"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'icon.png';
iconBlue.shadow = '';
iconBlue.iconSize = new GSize(19, 19);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'icon.png';
iconRed.shadow = '';
iconRed.iconSize = new GSize(19, 19);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["restaurant"] = iconBlue;
customIcons["bar"] = iconRed;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setMapType(G_SATELLITE_MAP);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 13);
// Change this depending on the name of your PHP file
GDownloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name, address, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 800px; height: 600px"></div>
</body>
</html>
(I suppose the php will be called by
GDownloadUrl("phpsqlajax_genxml.php", function(data) {
...
in the javascript part of the sourcecode of phpsqlajax_map.htm)
Now I need another php file and the code snipplets for it, which creates an input form where I can add some new locations to the google map. Following code is used to create the xml file here: http://detektors.de/maptest/phpsqlajax_genxml.php
The next step would be, trying to make an plugin for wordpress that I could easily post a blog entry with a new location on the same map, which displays already some other locations stored in the mysql database.
thanks!
<?php
require("phpsqlajax_dbinfo.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect ($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
Now I need another php file and the code snipplets for it, which creates an input form where I can add some new locations to the google map.
See: HTML FORMS
See: PHP $_POST
See: SQL INSERT INTO
most of your PHP code is going to be displaying the input form, handling the input form, and connecting to the database and performing an insert query.
[edit===start]
$query = "SELECT * FROM markers WHERE 1";
This is going to present a problem.. what is 1? you might want to compare with specific fields in the database. (markers)
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
#mysql_fetch_assoc should be mysql_fetch_assoc , I think syntax error.
Also, if you want to echo to file not console, change all echo to $file_output.= after $file_output=''; then echo $file_output (or file.. better yet return $file_output; ;))
Of course setting headers and not calling the loop as a function works a bit differently...