Displaying more than 1450 markers in Google Maps infowindows - google-maps

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

Related

How to display ganttchart with mysql database values in laravel?

I want to make a ganttchart, where I can retrieve data from database using mysql.
Highcharts do no include ganttchart, so i tried google charts. I am able to retrieve values from database and its can be seen in the page source, but not getting the output.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.1", {packages:["gantt"]});
google.setOnLoadCallback(drawChart);
<?php
$con = mysqli_connect("localhost","root","","db1") or die("could not connect");
$query= "select * from view_chart";
$qresult=mysqli_query($con,$query);
$results = array();
while($res = mysqli_fetch_array($qresult))
{
$results[] = $res;
}
$gan_data = array();
foreach($results as $result)
{
$gan_data[] = ($result['Brands']);
$gan_data1[] = ((int)$result['ratings']);
$gan_data2[] = ((int)$result['bigbazar']);
}
$gan_data = json_encode($gan_data);
$gan_data1 = json_encode($gan_data1);
$gan_data2 = json_encode($gan_data2);
mysqli_free_result($qresult);
?>
function drawChart() {
// var container = document.getElementById('gantt');
//var chart =new google.visualization.GanttChart(container);
alert('hello');
var data = new google.visualization.arrayToDataTable(<?=$gan_data?>);
data.addColumn( type: 'string', id: 'Brands' );
data.addColumn( type: 'number', id: 'ratings' );
data.addColumn( type: 'number', id: 'bigbazar' );
data.addRows([
<?php echo $gan_data; ?>,
<?php echo $gan_data1; ?>,
<?php echo $gan_data2; ?>]);
var options = {
height: 275
};
var chart = new google.visualization.GanttChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>

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

Blogger API not retrieving all the post from a blog

I have a travel blog with blogspot. I have a page which displays a map of the world with the path taken so far. To do this, I use the blogger API to retrieve the location of each post as follow:
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?callback=handleResponse&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU">
My issue is that it seems that only the last posts are retrieved and the first ones ignored. On the following link, the complete path should contain all the south of Argentina and be linked to the current path shown.
http://el-gato-lindo.blogspot.com/p/map.html
The complete code to generate the map is as follow:
<html>
<body>
<div id="content">
</div>
<div align="center" id="googleMap" style="height: 900px; width: 620px;">
</div>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry" type="text/javascript"></script>
<script>
var Lat = new Array();
var Lng = new Array();
var Place = new Array();
var TitlePost = new Array();
var UrlPost = new Array();
var DatePost = new Array();
// Get latitude/longitude from Blogger
function handleResponse(response) {
for(i=0; i< response.items.length; i++){
if(response.items[i].location != undefined){
Lat.push(response.items[i].location.lat);
Lng.push(response.items[i].location.lng);
Place.push(response.items[i].location.name);
TitlePost.push(response.items[i].title);
UrlPost.push(response.items[i].url);
DatePost.push(response.items[i].published);
}
}
}
// Distance btw two places in km
function calcDistance(p1, p2){
return (google.maps.geometry.spherical.computeDistanceBetween(p1,p2)/1000).toFixed(2);
}
// Name of months for date formatting
var m_names = new Array();
m_names.push("January");
m_names.push("February");
m_names.push("March");
m_names.push("April");
m_names.push("May");
m_names.push("June");
m_names.push("July");
m_names.push("August");
m_names.push("September");
m_names.push("October");
m_names.push("November");
m_names.push("December");
// Create the map based on locations retrieved from Blogger
function initialize(){
// Get all latitude and longitude
var pos = new Array();
// Get the path
for(var i=0; i<Lat.length; i++){
pos[i]=new google.maps.LatLng(Lat[i],Lng[i]);
}
// Get the last position
var lastpos=new google.maps.LatLng(Lat[0],Lng[0]);
// Create the map
var mapProp = {
center:lastpos,
zoom:4,
mapTypeId:google.maps.MapTypeId.TERRAIN,
navigationControl:true,
streetViewControl:false
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
// Create the path
var flightPath = new google.maps.Polyline({
path:pos,
strokeColor:"#EE0000",
strokeOpacity:0.6,
strokeWeight:7,
clickable:false,
map:map
});
// Create invisible marker at each destination
var markerPos = new Array();
var infowindow = null;
for(var i=0; i<pos.length; i++){
marker=new google.maps.Marker({
position:pos[i],
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale:5,
fillOpacity:0,
strokeOpacity:0
},
clickable:true,
map:map
});
// Click on marker: Show infowindow with articles
google.maps.event.addListener(marker, 'click', function() {
// Articles posted within a given distance from point clicked will be shown
var toldist = 2048 / Math.pow(2,map.zoom); //km
str = '<div id="infowindow_listposts">';
for(var j=0; j<pos.length; j++){
if(pos[j] === this.position){
var optplace = j;
str += "<h1>
" + Place[j] + "</h1>
<br>";
}
}
str += "<ul>";
for(var j=0; j<pos.length; j++){
var dist = calcDistance(pos[j],this.position);
if(dist < toldist){
date = new Date(DatePost[j]);
str += "<li> <h2>
<a href='" + UrlPost[j] + "'>" + TitlePost[j] + "</a> <i>(";
str += m_names[date.getMonth()] + " " + date.getDate() + ", ";
str += date.getFullYear() + ") </i></h2>
</li>
";
}
}
str += "</ul>
";
str += "<i> Articles shown were written less than ";
if(toldist >= 1)
str += toldist + "km away from ";
else
str += 1000*toldist + "m away from ";
str += Place[optplace] + ".</i>";
str += "</div>
";
if (infowindow){
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
content:str
});
infowindow.open(map,this);
});
markerPos.push(marker);
}
// Create the marker of last position
var lastmarker=new google.maps.Marker({
position:lastpos,
clickable:false,
map:map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?callback=handleResponse&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU">
</script>
</body>
</html>
Thanks a lot for your help! I am currently travelling and it is quite difficult to solve this issue!
Nicolas
Try replacing
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?callback=handleResponse&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU">
with
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts/default?redirect=false&start-index=1&max-results=500?callback=handleResponse&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU">

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.

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.