cron job - geocode address field to lat & long in mySQL database - mysql

Has anyone done this, or have an idea?
I have a real estate script that for whatever reasons (google mapping limits, script itself) only gets the coordinates for half of the listings. I want to run a script that of the lat & long field are empty the script will use the address, city, state to populate the lat & long fields.
THoughts?
Edit:
Here's a code from google, that does allow you to geocode for a database:
http://code.google.com/apis/maps/articles/phpsqlgeocode.html
<?php
require("phpsqlgeocode_dbinfo.php");
define("MAPS_HOST", "maps.google.com");
define("KEY", "abcdefg");
// 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());
}
// Initialize delay in geocode speed
$delay = 0;
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
// Iterate through the rows, geocoding each address
while ($row = #mysql_fetch_assoc($result)) {
$geocode_pending = true;
while ($geocode_pending) {
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "&q=" . urlencode($address);
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '%s' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
} else if (strcmp($status, "620") == 0) {
// sent geocodes too fast
$delay += 100000;
} else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocoded. ";
echo "Received status " . $status . "
\n";
}
usleep($delay);
}
}
?>
I'm not sure where to start getting this to work with my database and my lat & long rows (declat and declong)
Any help would be appreciated. Thanks!

The best approach is obviously parsing the response and looking for the error code returned.
The most usual reason for this happening is
The requests going out too fast (add some throttling to your script)
Unicode characters like ÄÖÜ Umlauts being encoded wrongly
By the way, what you doing may be a violation of Google's Terms of Service:
Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited. For complete details on allowed usage, consult the Maps API Terms of Service License Restrictions.

I had the same requirement and got it working eventually:
This geocodes the addresses:
<?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 this generates the map (which I also cluster but you should be able to take that out):
<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 cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.4788, -3.9551),
zoom: 6,
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP file
downloadUrl("<?php bloginfo('stylesheet_directory'); ?>/phpsqlajax_genxml.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
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster);
});
}
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>

You are allowed 2500 geocodes per day. That's is a fair amount, but you can't just bombard the service with your requests. You need to provide a delay between each request, or else it will start blocking service.
Once you geocode, you should store the value within the database and mark it as geocoded, so you don't have to request it again. Then you can just geocode the rest as time goes on.

Related

Displaying more than 1450 markers in Google Maps infowindows

I have already make some GIS web using googlemaps. but I have some trouble. I have to displayed about 1500 - 2500 marker and have infowindows onclick. 2 days before, everything fine, but when i add more and much detail in infowindows (before only have 4 detail info like name, address, etc and now there is 9 detail info), the marker did not appear. I am using Json message function to get value from database and displayed in infowindows. if it's 1450 markers, it's work fine, but when markers more than that, the markers did not displayed on map. does it memory cache or cookies problem ?? Please help. Thanks. I am using googlechrome, Postgre database, PHP and googlemaps api v3.
<?php
require ('config.php');
$rayon = $_POST['rayon'];
$cabang = $_POST['org_id'];
//echo "$rayon, $cabang, $rayonhasil";
$sql = "SELECT distinct org_id, cp_customer_site_use_id, customer_name, address, postal_code, city, cp_rayon_name, icon_rayon, attribute16, attribute17 FROM hasilgis";
$data = pg_query($sql);
$json = '{"enseval": {';
$json .= '"customer":[ ';
while($x = pg_fetch_array($data)){
$json .= '{';
$json .= '"id_customer":"'.$x['org_id'].'",
"id_photo":"'.$x['cp_customer_site_use_id'].'",
"postal_code":"'.$x['postal_code'].'",
"nama_customer":"'.htmlspecialchars($x['customer_name']).'",
"city":"'.htmlspecialchars($x['city']).'",
"address":"'.htmlspecialchars($x['address']).'",
"nama_rayon":"'.htmlspecialchars($x['cp_rayon_name']).'",
"icon":"'.$x['icon_rayon'].'",
"x":"'.$x['attribute16'].'",
"y":"'.$x['attribute17'].'"
},';
}
$json = substr($json,0,strlen($json)-1);
$json .= ']';
$json .= '}}';
echo $json;
?>
<script type="text/javascript">
function initialize(){
var peta;
var x = new Array();
var y = new Array();
var customer_name = new Array();
var cp_rayon_name = new Array();
var icon = new Array();
var photo = new Array();
var city = new Array();
var address = new Array();
var postal_code = new Array();
// posisi default peta saat diload
var lokasibaru = new google.maps.LatLng( -1.2653859,116.83119999999997);
var petaoption = {
zoom: 5,
center: lokasibaru,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
var infowindow = new google.maps.InfoWindow({
content: ''
});
// memanggil function untuk menampilkan koordinat
url = "json.php";
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function(msg){
for(i=0;i<msg.enseval.customer.length;i++){
x[i] = msg.enseval.customer[i].x;
y[i] = msg.enseval.customer[i].y;
customer_name[i] = msg.enseval.customer[i].nama_customer;
cp_rayon_name[i] = msg.enseval.customer[i].nama_rayon;
icon[i] = msg.enseval.customer[i].icon;
photo[i] = msg.enseval.customer[i].id_photo;
city[i] = msg.enseval.customer[i].city;
address[i] = msg.enseval.customer[i].address;
postal_code[i] = msg.enseval.customer[i].postal_code;
var point = new google.maps.LatLng(parseFloat(msg.enseval.customer[i].x),parseFloat(msg.enseval.customer[i].y));
var gambar_tanda = 'assets/images/'+msg.enseval.customer[i].icon+'.png';
var photo_cust = '<img src="assets/images/foto_cust/'+msg.enseval.customer[i].id_photo+'_1.jpg" style="width:200px;height:120px;"/>';
//var nm_cust = msg.enseval.customer[i].nama_customer;
//var nm_rayon = , msg.enseval.customer[i].nama_rayon;
var html = '<b>' + customer_name[i] + '</b><br/>'+city[i]+ ', '+address[i]+', '+postal_code[i]+'<br/>' + cp_rayon_name[i] + '<br/>' + photo_cust;
tanda = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_tanda,
clickable: true
});
bindInfoWindow(tanda, peta, infowindow, html );
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function bindInfoWindow(tanda, peta, infowindow, data) {
google.maps.event.addListener(tanda, 'click', function() {
infowindow.setContent(data);
infowindow.open(peta, tanda);
});
}
function reload(form){
var val=form.org_id.options[form.org_id.options.selectedIndex].value;
self.location='main_page.php?cabang=' + val ;
}
</script>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>
<body>
<div id="wrapper"><!-- #wrapper -->
<header><!-- header -->
<br><br><br>
<h1></h1>
</header><!-- end of header -->
<section id="main"><!-- #main content area -->
<div id="map_canvas" style=" align: left; width:1000px; height:500px"></div><br>
<?php require ('config.php');
#$cabang=$_GET['cabang'];
/*if(strlen($cabang) > 0 and !is_numeric($cabang)){
echo "Data Error";
exit;
}*/
$quer2=pg_query("SELECT DISTINCT orgid FROM epmgis order by orgid");
if(isset($cabang) and strlen($cabang)){
$quer=pg_query("SELECT DISTINCT nm_rayon FROM epmgis where orgid=$cabang order by nm_rayon");
}
else{$quer=pg_query("SELECT DISTINCT nm_rayon FROM epmgis order by nm_rayon"); }
echo"<table>";
echo"<tr>";
echo "<form method=post name=f1 action='proses_map.php'>";
echo " <td>Silahkan Pilih Kode Cabang </td><td>:</td><td><select name='org_id' onchange=\"reload(this.form)\"><option value=''></option>";
while($noticia2 = pg_fetch_array($quer2)) {
if($noticia2['orgid']==#$cabang){echo "<option selected value='$noticia2[orgid]'>$noticia2[orgid]</option>"."<BR>";}
else{echo "<option value='$noticia2[orgid]'>$noticia2[orgid]</option>";}
}
echo "</select></td></tr>";
echo"<br>";
echo "<tr><td>Silahkan Pilih Rayon</td><td>:</td><td><select name='rayon'><option value=''></option>";
while($noticia = pg_fetch_array($quer)) {
echo "<option value='$noticia[nm_rayon]'>$noticia[nm_rayon]</option>";
}
echo "</select></td></tr>";
echo "<tr><td><input type=submit value=Submit>";
echo "</form>";
echo"</td></tr>";
echo"</table>";
?>

Changing from Google maps api v2 to v3

I've been using Google geocoding v3 for about 6 months but all of a sudden it's stopped working (I get a 610 error). It's only stopped in the last week or so.
Then I came across this (see the pink box at the top of the page!): https://developers.google.com/maps/documentation/geocoding/v2/
I've read through all the documentation and not sure where to start!
I'm hoping it's a small change as it's taken a long time to get this far, can anyone help?
[See the full site here][1]
UPDATE:
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("teamwork_poh", $con);
$company = get_the_title();
$address = get_field('address_line_1');
$city = get_field('town_/_city');
$post_code = get_field('post_code');
$link = get_permalink();
$type = get_field('kind_of_organisation');
$sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
$row_dup = mysql_fetch_assoc(mysql_query($sql,$con));
if ($row_dup['cnt'] == 0) {
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '".$type."', '".$link."')");
}
wp_reset_query();
require("database.php");
define("MAPS_HOST", "maps.googleapis.com");
define("KEY", "(my key)");
// 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());
}
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
//Initialize delay in geocode speed
$delay=0;
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/json?address=";
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {
$geocode_pending = true;
while ($geocode_pending){
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "" . urlencode($address) ."&sensor=false";
sleep(0.1);
$json = file_get_contents($request_url);
$json_decoded = json_decode($json);
$status = $json_decoded->status;
if (strcmp($json_decoded->status, "OK") == 0) {
$geocode_pending = false;
$lat = $json_decoded->results[0]->geometry->location->lat;
$lng = $json_decoded->results[0]->geometry->location->lng;
// echo 'here';
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '%s' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
echo $id;
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
}
else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocode. ";
echo "Received status " . $status . "\n";
}
// usleep($delay);
}
}
}
As you are storing the coordinates in database it would be best to geocode when you insert new record.
ie
require("dbinfo.php");//Your database parameters
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
//Prepare query
$name = "%".$company."%";//Wildcard for PDO paramerter
$countSql = "SELECT COUNT(*) FROM markers WHERE `name` LIKE ?";
$countStmt = $dbh->prepare($countSql);
// Assign parameter
$countStmt->bindParam(1,$name);
//Execute query
$countStmt->execute();
// check the row count
if ($countStmt->fetchColumn() == 0) { #1 EDIT changed >0 to ==0
echo "No row matched the query."; //EDIT From Row
$q =$address.','.$city.','.$post_code.',UK';
echo "\n";
$base_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=";
$request_url = $base_url.urlencode($q)."&sensor=false";
$xml = simplexml_load_file($request_url) or die("url not loading");
if($xml->status=="OK"){#2
// Successful geocode
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
$insertSql ="INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES (?,?,?,?,?,?)";
$insertStmt = $dbh->prepare($insertSql);
// Assign parameter
$insertStmt->bindParam(1,$company);
$insertStmt->bindParam(2,$address);
$insertStmt->bindParam(3,$lat);
$insertStmt->bindParam(4,$lng);
$insertStmt->bindParam(5,$type);
$insertStmt->bindParam(6,$link);
//Execute query
$insertStmt->execute();
} #2
else{
"No rows inserted.";
}#2
} #1
else {#1
echo "Rows matched the query."; //EDIT From No row
} #1
}// End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myFile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
I have converted your code to PDO as it is advisable to stop using mysql_functions as these a deprecated.
I have left you to implement how you will deal with geocoding not returning coordinates. You can also check and deal with the following status codes
OVER_QUERY_LIMIT
ZERO_RESULTS
REQUEST_DENIED
INVALID_REQUEST
See pastebin For status code implementation
Going by our earlier comments, there are just a couple of changes required that should get you back on your feet.
These are, changing the address for v3 geocoding
define("MAPS_HOST", "maps.googleapis.com");
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?";
$request_url = $base_url . "address=" . urlencode($address) . "&sensor=false";
And secondly changing the path in the returned xml file for setting lat/long
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
Can be completely replaced with
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
The next piece about stopping it from going over geocoding limits. What you need to do is set a simple check before you run through the geocoding.
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {// add this line
$geocode_pending = true;
while ($geocode_pending){
//do geocoding stuff
}
}
}// add this close
}

Query fails when I use where

I have this code
$marker = 'werkz';
$sql = "SELECT name, marker FROM sidebar";
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo'<option>' . $r[name] . '</option>';
}
It works but when I add WHERE marker = $maker; the query fails.
What is the problem?
since you are using PDO, do it like this when passing parameter.
$marker = 'werkz';
$sql = "SELECT name, marker FROM sidebar WHERE marker = ?";
$q = $db->query($sql);
$q->bindParam(1, $maker);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo'<option>' . $r[name] . '</option>';
}
$market is a string. So you should put it between '
something like ... where marker='".$marker."'";

Google MAPs api v2 AJAX not working

My code is not working what is going wrong I can't understand...my code is:
/* =================Call.php========================*/
<?php
/* Include settings My mysql database */
include ("config.php");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>GG-Tracker (GSM and GPS location combined)</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=myAPIKey&sensor=true" type="text/javascript"></script>
<?php
echo "
<script type=\"text/javascript\">
var map;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById(\"map\"));
downloadUrl(\"phpsqlajax_genxml.php\", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName(\"marker
\");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute(\"lat\"));
var lon = parseFloat(markers[i].getAttribute(\"lon\"));
var html = \"<b>\" + \"</b> <br/>\" ;
var marker = new GMarker(new GLatLng(lat, lon));
map.addOverlay(marker);
}
}
}
}
function downloadUrl(url, callback) {
if (window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else
{
request=new ActiveXObject(\"Microsoft.XMLHTTP\");
}
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing();
callback(request, request.status);
}
};
request.open(\"GET\", url, true);
request.send();
}
function doNothing() {}
</script>
";
?>
</head>
<body onload="load()" onunload="GUnload()">
<center>
<div id="map" style="width: 800px; height: 600px"></div>
</body>
</html>
/* End of =============Call.php===============*/
My phpsqlajax_genxml.php for genrating XML is:
/* Start of ===========phpsqlajax_genxml.php=============== */
<?php
require("phpsqlajax_dbinfo.php");
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
$connection=mysql_connect ($dbhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$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());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("tid",$row['TID']);
$newnode->setAttribute("devid",$row['DevID']);
$newnode->setAttribute("ldate",$row['LDate']);
$newnode->setAttribute("ltime",$row['LTime']);
$newnode->setAttribute("lat", $row['Lat']);
$newnode->setAttribute("lon", $row['Lon']);
$newnode->setAttribute("speed", $row['Speed']);
}
echo $dom->saveXML();
?>
/*=========End of=============phpsqlajax_genxml.php*/
My Database information file is: phpsqlajax_dbinfo.php
/*=========Start of=== phpsqlajax_dbinfo.php============*/
<?php
$dbhost = "localhost";
$username="root";
$password="";
$database="mygps";
$gmaps = "AIzaSyCRf9drwSYjBSeKpvSkEHFKqX_yBpq-Tkk";
?>
/*===========End of phpsqlajax_dbinfo.php==============*/
the above three files cant work.
If I run only phpsqlajax_genxml.php file to generate XML it is working
I can generate XML but it cannot downloaded through JAVA - I think AJAX call is not
working....
What to do auto reload marker from MySQL on some time interval without
reloading whole page like Live Tracking.....
Please Help Me My above code is not working
Thanks for Reading
Pradip
The V2 API is deprecated and you should migrate to V3 of the API.
https://developers.google.com/maps/documentation/javascript/
Is there any reason for using php-echo to output HTML-source?
However, if the code above is really what you actually use, you have a problem here:
var markers = xml.documentElement.getElementsByTagName(\"marker
\");
the line-break will break your script, remove it.

Javascript, php, mysql, and json has me stumped

Been reading up on php and json and am trying this piece of code which is not working and I can't figure out why. Any help is appreciated.
I call a JavaScript function from my html file onLoad(). That function is
function getSched()
{
$.post("schedlz.php", {dat: ""+inputString+"", action: "searchSched"}, function(data)
{
var y="";
if(data.length >0)
{
var obj = JSON.parse(data);
y = getRes (data);
}
else //some error handler
}
function getRes(data)
{
var str="";
var obj = JSON.parse (data);
alert (data.length + " | " +obj + " | ");
return str;
}
In schedlz.php file
$conn = getDbConn();
mysql_select_db("myschedulez", $conn);
$result = mysql_query($sql,$conn) or die('Error: ' . mysql_error());
$rows = array();
while ($r = mysql_fetch_assoc($result))
{
// $rows['schedulez'][] = $r;
$rows[] = $r;
}
echo json_encode($rows);
mysql_close($conn);
The problem is that I get the data back in correct json format but when I parse it, there is no Object. What could be going wrong here?
You need to add the dataType parameter to your $.post, which in your case is json.
I'm also not sure if you closed $.post correctly in your sample so I'm adding the closing ); as well.
function getSched()
{
$.post("schedlz.php",
{dat: ""+inputString+"", action: "searchSched"},
function(data) {
var y="";
if(data.length >0)
{
var obj = JSON.parse(data);
y = getRes (data);
}
else {} //some error handler
},
'json'
);
}