I have a problem with google maps markers. I want to use polish characters in the names of the markers. As i have in my db. This is the file which i use to create proper (afaik) XML.
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 ';
$test = $row['name'];
//$test2 = string utf8_encode ( string $test );
echo 'name="' . $test . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'city="' . $row['city'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
I get proper output from my db using this file (browser display polish characters properly) but when i create a map using:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBdj-LlQrTCj6bQcAq4fxONy9MaZcXvfc8"
type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(50.046465, 19.913828),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("markergen.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("city");
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
});
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"></div>
</body>
</html>
Then i get whole data, but without correctly displayed polish characters.
I know that i should probably use
string utf8_encode ( string $data )
but i did try to put it in first file to convert data and fail.
So my question is where i should put it exactly into my code? Or is there any other/better option to do this.
EDIT:
I'm now trying to use DOM objects like this:
<?php
require("../test1/phpsqlinfo_dbinfo.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$mysqli = new mysqli("localhost", $username, $password, $database);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = $mysqli->query($query);
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysqli_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("city", $row['city']);
}
echo $dom->saveXML();
?>
But now i have marker inside of marker in results like: <marker><marker>...</marker></marker> with data ofc. How to fix it? Still i'm not sure that data are correctly encoded but should be.
No, you should not use utf8_encode().
You should however use ext/mysqli or ext/pdo (not the old, depreacted and removed ext/mysql). Set the connection encoding to UTF-8 to get all strings as UTF-8 from the database.
Then use an XML library (DOM or XMLWriter) to generate the XML output. The libraries will encode/escape special characters as needed.
It will provide the missing XML declaration, too.
Related
I have made a database in MySQL with some information and long/lat data in it. I would like this data to appear on my google maps page as markers, so that I do not have to manually add markers to a script.
I have followed several tutorials and have tried several scripts, with the one shown below being the only one that didn't come up with errors for me. However, the markers do not appear on the map. I have mainly followed instructions from this link: https://developers.google.com/maps/documentation/javascript/mysql-to-maps
My data does appear on the xml file as it states in the tutorial, having a look at my sourcecode for the map I find the following error at line 54 of the index.html script:
Uncaught ReferenceError: customLabel is not defined
I have tried fixing this, but I end up messing up the entire script. My question is, could anyone help me fix this error so that my markers appear on the map created in the index.html file?
I have 3 separate scripts: a "config.php" for my log in details, a "maps_xml.php" to call the data and an "index.html" to make the map and add the data as markers.
Config script:
<?php
$username="mydatabase_username";
$password="12345";
$database="mydatabase";
?>
Maps_XML.php script:
<?php
require("config.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=mysqli_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysqli_error());
}
// Set the active MySQL database
$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
die ('Can\'t use db : ' . mysqli_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM userlocations WHERE 1";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Invalid query: ' . mysqli_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo "<?xml version='1.0' ?>";
echo '<markers>';
$ind=0;
// Iterate through the rows, printing XML nodes for each
while ($row = #mysqli_fetch_assoc($result)){
// Add to XML document node
echo '<marker ';
echo 'id="' . $row['id'] . '" ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo '/>';
$ind = $ind + 1;
}
// End XML file
echo '</markers>';
?>
*
Index.html script:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>User locations</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<html>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(51.153844, 5.942341),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('maps_xml.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
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>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_APIKEY &callback=initMap">
</script>
</body>
</html>
Completely stumped here. Can't get ' (apostrophe) to display correctly... Used the tutorial from google Google Maps Tutorial to create a map from my database. It connects to my database, creates an XML file and then that XML file is referenced to create the map.
The following code is my PHP file that creates the XML. See the escape code.
<?php
// Escape Characters
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;
}
$servername = "localhost";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Select all the rows in the markers table
$sql = "
SELECT *
FROM table1
WHERE status = 'ACTIVE'";
$result = $conn->query($sql);
if (!$result) {
die('Invalid query: ' . mysqli_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo "<?xml version='1.0' ?>";
echo '<markers>';
$ind=0;
// Iterate through the rows, printing XML nodes for each
while ($row = #mysqli_fetch_assoc($result)){
// Add to XML document node
echo '<marker ';
echo 'fac_id="' . $row['fac_id'] . '" ';
echo 'fac_name="' . parseToXML($row['fac_name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'region="' . $row['region'] . '" ';
echo '/>';
$ind = $ind + 1;
}
// End XML file
echo '</markers>';
?>
Here is a line from the XML file that was created above. The apostrophe is represented as '
<marker fac_id="123" fac_name="St. Luke's MC" address="1800 East Van Buren Street" lat="33.451542" lng="-112.043129" region="West C"/>
Below is the html file (not working as I removed personal data) used to create the actual map. I really have no experience in javascript, so I am unsure why the apostrophe is not decoded?
Screenshot of improperly displayed apostrophe:
Google Map Screenshot
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Using MySQL and PHP with Google Maps</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var customLabel = {
'East A': {
label: 'A'
},
'West C': {
label: 'C'
},
'North D': {
label: 'D'
},
'East K': {
label: 'K'
},
'North M': {
label: 'M'
},
'South S': {
label: 'S'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(35.845424, -93.738202),
zoom: 4.75
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('http://example.com/xmlmaker.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var fac_id = markerElem.getAttribute('fac_id');
var fac_name = markerElem.getAttribute('fac_name');
var address = markerElem.getAttribute('address');
var region = markerElem.getAttribute('region');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = fac_name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[region] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
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>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=ABC1234567890&callback=initMap">
</script>
</body>
</html>
Your parseToXML($htmlStr) function is nuking & substitutions from earlier replacements because after it substitutes, say, ' for ', it then proceeds to ruin ' by replacing & with &.
All of those characters don't have to be replaced in all contexts. See Simplified XML Escaping, and refine your parseToXML() function and where it's called accordingly.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I have this code in PHP. i works fine:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tsunami_simulation";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//========================================================
$sql='SELECT a.Household_Name, b.Latitude, b.Longitude FROM household a, location b WHERE a.Household_ID = b.Household_ID;';
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
for($i=0;$i<$num_rows;$i++){
$row=mysql_fetch_row($result);
$location[]= $row[0].', '.$row[2].', '.$row[1].','.($i+1);
//echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
}
}else{echo "0 results";}
?>
now, what i want to do is access the array result from this PHP file in javascript. i tried using JSON.parse(). but i doesn't work.
i used this piece of code: var locations = '<?php echo json_encode($location); ?>'; i does not give errors. followed by locations = JSON.parse(locations) and it returns <?php echo json_encode($location); ?> this and not the data. how can i get the proper data, any methods will do as long as it works, please help me. btw, i want to get the array from database in wamp and put markers on googlemap using the coordinates from the array. help me please!..
EDIT: There's is the other code where i have to access the data:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>New 1 -- Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?v3"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<?php include 'Location.php';?>
<script type="text/javascript">
var locations = <?php echo json_encode($location, JSON_HEX_TAG); ?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(6.40, 125.60),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
loc_array = locations[i].split(",");
marker = new google.maps.Marker({
position: new google.maps.LatLng(loc_array[1], loc_array[2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(loc_array[0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
$location[]= array($row[0], $row[2], $row[1], $i+1);
and then
var locations = <?php echo json_encode($location, JSON_HEX_TAG); ?>
Note: no JSON.parse needed, no quotes, and especially not manual concatenation of variables to form a quasi-array.
EDIT: JSON_HEX_TAG is highly recommended, if you have PHP 5.3.3+, as plain json_encode is not quite secure.
I am trying to build a website that displays a google map with a user location (lat/long) from a php service that I wrote.
I already have a php script that gets the lat/long from a mobile app (via POST from the client), stores it in a DB, and read it back from the DB into two variables, let's call them $lat and $long. To make sure I have the right values in $lat and $long, I did a simple echo and got the two values.
I am struggling with understanding how to read these values from my index.html script. All the examples that I have seen suggest keeping the php code in the html file but I would rather keep them separate. I am also not sure how to assign these values to parameters in HTML/Javacript so I can actually display them on the map.
So my questions are:
1. how do I call that php file from HTML?
2. and how do I read $lat and $long from the php service and assign them to parameters in HTML/Javascript that I can display on the map?
EDIT: here is my PHP code and my index.html (Which is a 1:1 copy from the Google Maps v3 docs).
location.php:
$content = file_get_contents('php://input');
$post_data = json_decode($content , true);
$lat = $post_data['lat'];
$long = $post_data['long'];
//CONNECT TO MYSQL
$con1 = mysql_connect("localhost", "francesco", "bbbbbb", "location111");
if ($con1->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db_selected = mysql_select_db('location111');
if(mysql_select_db('location111')) { echo 'true '; } else { echo 'falise'; }
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
if (!empty($lat)) {
$sql = "INSERT INTO LocationInfo (latitude, longitude)
VALUES ('$lat', '$long');";
mysql_query($sql) or die ('Error updating database: ' . mysql_error());
}
$read_query = "SELECT * FROM LocationInfo;";
$results = mysql_query($read_query) or die ('Error reading from database: ' . mysql_error());
$column = array();
while($row = mysql_fetch_array($results)){
$column[] = $row;
}
$current_lat = $column[sizeof($column) - 1]['latitude'];
$current_long = $column[sizeof($column) - 1]['longitude'];
echo $current_lat;
echo $current_long;
?>
index.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>My GeoLocation</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
function initialize() {
// var myLatlng = new google.maps.LatLng(40.7127840,-74.0059410);
var mapOptions = {
zoom: 14
//mapTypeId: google.maps.MapTypeId.ROADMAP
//center: myLatlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
First of all, if you want to display something in template with php, it must have .php extension, not .html
You can then use your php inside of inline javascript like that:
<script type="text/javascript">
var long = "<?php echo $long;?>";
var lat= "<?php echo $lat;?>";
</script>
Or you can use Ajax on other hand
To all, Thanks in advance for helping out..
Trying to get this google script working, done both tutorials and I cannot get the map pins from the database showing up on the map. XML is valid, connected to db, just the pins... Code is as follows
phpsqlajax_genxml2.php
<?php
header("Content-type: text/xml");
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 ('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 6";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// 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>';
?>
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;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml2.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>
phpsqlajax_dbinfo.php
<?
$username="$username";
$password="$password";
$database=" $database";
?>
Thanks for the help!
Here is the output url: http://opensourcefish.com/phpsqlajax_map_v3.html
Let me know what else you need if anything!
Ok, changed the php to echo xml instead of using DOM and I get invalid xml... I think.. Now what? Or how do I enable DOM_xml b/c i'm totally snowed by that one... Thanks again ya'll
Edit: added the db php file as well and updated the others as suggested
Your xml feed isn't working.
opensourcefish.com/phpsqlajax_genxml.php
gives:
Fatal error: Call to undefined function domxml_new_doc() in /home1/mac4281/opensourcefish.com/phpsqlajax_genxml.php on line 5
See this question for details about that issue.
The xml being generated is invalid. Take out the extra bracket from the marker tag:
echo '<marker ';
This way the attributes are correctly placed within the marker tag.
Edit:
Also, add the following header in your phpsqlajax_dbinfo.php file after the <? tag:
header("Content-type: text/xml");
Solution 2:
Instead of echoing the xml data, put it in a xml file:
$data= '<markers> ';
while ($row = #mysql_fetch_assoc($result)){
$data1 = '<marker ' . 'name="' . parseToXML($row['name']) . '" ' .
'address="' . parseToXML($row['address']) . '" ' . 'lat="' . $row['lat'] . '" ' .
'lng="' . $row['lng'] . '" ' . 'type="' . $row['type'] . '" ' . '/>';
}
$data2 = '</markers>';
$xmlData = $data. $data1 . $data2;
file_put_contents("xmldata.xml", $xmlData);
and then load it in the html through:
downloadUrl("xmldata.xml", function(data) {
Also add the following to the html as we need to load the php file first:
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
And the following line right before downloadUrl("xmldata.xml", function(data) { :
$.get("phpsqlajax_genxml2.php");
So all the files now look like this: https://gist.github.com/anonymous/7010144
To all: Thank you so much! I got it working and it turned out to be a header issue and a really dumb mistake. Lesson to all you "copy/paste rangers" out there, READ YOUR CODE!!!
Thanks a TON Rohit for all the help. Your were right early on, it was simply a duplicate header.. I copied but forgot to delete what I copied and it was down hill from there. Thanks again guys!!