Google MAPs api v2 AJAX not working - google-maps

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.

Related

How to add latest TimesStamp to Google Gauge

I need help adding latest TimesStamp to page that displays Google gauge. I have made gauge work and auto refresh without the need to refresh the page, but now I need to display on it, or next to it when the latest entry in database was made (displaying TimesStamp of value that is currently displayed in gauge). Here's my code so far:
Chart.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 800, height: 240,
greenFrom: 98, greenTo: 100,
yellowFrom:90, yellowTo: 98,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="chart_div" style="width: 800px; height: 240px;"></div>
</body>
</html>
And here's getdata.php
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
}
mysqli_close($conn);
// write data array to page
echo json_encode($data);
?>
we need to include the timestamp in the data we return from php.
first, add the field to the select statement, here...
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
next, we use a variable to save the timestamp...
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
then, in the while loop, we save the value of the timestamp...
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
finally, we combine both the chart data and timestamp in an object to send to the page.
$data = array('rows' => $data, 'timestamp' => $stamp);
following is the updated php snippet...
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
mysqli_close($conn);
// write data array to page
$data = array('rows' => $data, 'timestamp' => $stamp);
echo json_encode($data);
?>
then on the html page, we need to adjust how we receive the data...
to receive the chart data, we need to use the 'rows' property from the data.
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows); // <-- add .rows
and we can receive the timestamp as follows...
jsonData.timestamp
not sure how you want to display the timestamp, here a <div> is used.
so to update the new <div> element...
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
following the updated html snippet...
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows);
chart.draw(data, options);
// update timestamp
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="timestamp"></div>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>

Get data from database and append data to aframe

I want to get data from database and append that data to aframe. I did and data is getting from the database but not appending to the aframe scene. Here is my working flow.
This index file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<a-scene id="scene">
<a-camera id="camera" position="0 0 2" >
</a-camera>
<a-sky color="#000"></a-sky>
</a-scene>
<script>
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "data.php";
var asychronous = true;
ajax.open(method,url,asychronous);
ajax.send();
ajax.onreadystatechange = function(){
if(this.readyState==4 && this.status==200){
var data = JSON.parse(this.responseText);
console.log(data);
var html = "";
var username = "";
for(var i=0;i<data.length;i++){
username = data[i].username;
html += "<a-scene>";
html += +username;
html += "</a-scene>";
}
var totalText1 = document.createElement('a-text');
totalText1.setAttribute('position',{x:0, y:0, z:0});
totalText1.setAttribute('color',"#fff");
totalText1.setAttribute('value',username);
totalText1.setAttribute('scale',{x:1.6, y:1.6, z:1.6});
document.getElementById("scene").appendChild(totalText1);
}
}
</script>
</body>
</html>
Here is data.php file
<?php
$conn = mysqli_connect("localhost","root","","test");
$query = "SELECT * FROM usertest WHERE language='english'";
$result = mysqli_query($conn,$query);
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data = $row;
}
echo json_encode($data);
?>
Data retrieving is okay.But is there any way to append those data to aframe scene?
Double check the entity is actually getting appended to the scene. It looks right. Check the Inspector (ctrl/alt/i) or DOM Inspector or query selector from console. The 0/0/0 position might just make it hard to see.

Ajax GET content from php page

Hi I have a table which I am trying to update with a call to a MySQL database in a separate php page. This separate page loops through a result set and builds the table through a series of echos. In the main page I am trying to insert that echoed content into a div.
This is all kicked off by the user selecting an option from a drop down box.
This is the separate php page. (It works fine when i manually type in the GET parameters, it is the link between the two pages which doesn't seem to work)
tableGetter.php
<?PHP
$user_name = "rocketeermus_pr";
$password = "zuluhead2";
$database = "rocketeermus_pr";
$server = "pdb1.awardspace.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
echo "Bonjour";
if (isset($_GET['composer'])){
echo "Helloooo";
if ($db_found) {
echo "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$SQL = "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
echo "<table class=\"sortable\" id=\"moder\" width=\"800\">";
echo "<th>TITLE</th><th>COMPOSER</th><th>VOICING</th><th>PRICE</th><th></th></tr>";
while ( $db_field = mysql_fetch_assoc($result) ) {
echo "Hi.";
echo "<tr><td>{$db_field['Title']}</td><td>{$db_field['Composer']}</td><td>{$db_field['Voicing']}</td><td>";
echo money_format("%n", $db_field['Price']);
echo "</td><td> <div class=\"product\"> <input value=\"{$db_field['Title']}\" class=\"product-title\" type=\"hidden\"> <input value=\"0.5\" class=\"product-weight\" type=\"hidden\"> <input value=\"{$db_field['NoVox']}\" class=\"googlecart-quantity\" type=\"hidden\"> <input value=\"{$db_field['Price']}\" class=\"product-price\" type=\"hidden\"> <div title=\"Add to cart\" role=\"button\" tabindex=\"0\" class=\"googlecart-add-button\"> </div> </div> </td></tr>";
}
echo "</table>";
mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
?>
And here is the important stuff from the main page:
Javascript:
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
var queryString1 = "";
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
// only if http status is "OK"
if (req.status == 200)
{
var new1 = document.getElementById('composer').value;
queryString1 = "?composer=" + encodeURIComponent(new1);
console.log (queryString1);
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}
function getXMLHTTP() {
var xmlhttp;
if(window.XMLHttpRequest){ //For Firefox, Mozilla, Opera, and Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){ //For ie
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
html:
<div id="menus">
<table>
<tr>
<td><form action=""">
<select name="composer" id ="composer" onchange="getdata();">
<?php
$user_name = "***";
$password = "****";
$database = "****";
$server = "****.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT DISTINCT Composer FROM catalogue ORDER BY Composer";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
while ( $db_field = mysql_fetch_assoc($result) ) {
?>
<option id="composer" onchange="getdata();" value="<?php echo $db_field['Composer'];?>">
<?php
echo $db_field['Composer'];
?>
</option>
<?php
}
}
?>
</select>
</form></td>
</tr>
</table>
</div>
<div id="table">
<?php include("tableGetter.php"); ?>
</div>
The html on the main page works fine, the drop down menu fills up nicely with all the distinct composer names in the database. When an option in the menu is selected the only thing echoed in the "table" div is "Bonjour". It's not getting further than if (isset($_GET['composer'])) in the tableGetter.php page. I'm printing out the queryString1 variable (The get parameters) which is requested in the getData() function and it reports: ?composer=Animuccia%2C%20Paulo which works perfectly when loading the page manually. It just won't work dynamically!
Anybody know what's going on here?
You aren't setting queryString1 before sending the AJAX request. Try this rewrite of getdata().
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
var new1 = document.getElementById('composer').value;
var queryString1 = "?composer=" + encodeURIComponent(new1);
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}

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>";
?>

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

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.