Google Map, API, If address not found locate Zip

Hello,

Below is my code and I am getting an error because a lot of homes are not listing street addresses. I would like if it could say...

if property not found then show zip.

I would love any help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  	<STYLE type=text/css>
	BODY {
		MARGIN: 0px; 
		BACKGROUND-COLOR: #ffffff;
		font-family:Verdana, Arial, Helvetica, sans-serif;
		font-size:10px;
	}
	</STYLE>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Map</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=ABQIAAAANy3TVrsW5WpnNvimGWqO-hQS_tGb29H7YG-S9HZO4R09DIw8tBTpAIwwit7hyJMO07C-IEjpbTLQpA" type="text/javascript"></script>
    <script type="text/javascript">
 
    var map = null;
    var geocoder = null;
 
    function load() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setMapType(G_PHYSICAL_MAP);
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
geocoder = new GClientGeocoder();
}
    }
 
    function showAddress(address, address2, dispaddress, lat, lng, bRetried) {
 
	  if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
			  if (bRetried)
              	alert(address + " not found");
			  else
			  	showAddress(address, address2, dispaddress, lat, lng, 1);
				
            } else {
			  var dIconConstructor = new GIcon();
			  dIconConstructor.image = 'imagesmain/gmapicon.png';
			//  dIconConstructor.shadow = 'images/SS-GMap-Icon-5-shadow.png';
			  dIconConstructor.iconSize = new GSize(35, 40.0);
			  dIconConstructor.shadowSize = new GSize(80.0, 51.0);
			  dIconConstructor.iconAnchor = new GPoint(20, 32.0);
			//  dIconConstructor.infoWindowAnchor = new GPoint(55.0, 4.0);
			  var dIcon = new GIcon(dIconConstructor);
 
			  
			  map.addControl(new GSmallMapControl());
			  //map.addControl(new GMapTypeControl());
              
			  map.setCenter(point, 13);
			  
			  var marker = new GMarker(point, dIcon);
			  			  
 
				
              map.addOverlay(marker);
              
			  
			  
				
            }
          }
        );
      }
    }
	
	function searchAddr() {
		<?
		if ($_GET["margin"]) {
			$sDisplay = "<div style='margin:".$_GET["margin"]."px'>".$_GET["d"]."</div>";
		}
		else {
			$sDisplay = $_GET["d"];
		}
		?>
		<?
		if (!$_GET["a2"]) {
			$a2 = split(",", $_GET["a2"]);
			$_GET["a2"] = $a2[0];
		}
		?>
		showAddress("<?=$_GET["a"]?>","<?=$_GET["a2"]?>","<?=$sDisplay?>","<?=$_GET["lat"]?>","<?=$_GET["lng"]?>", 0);
	}
    </script>
 
  </head>
 
  <body onload="load(); searchAddr();" onunload="GUnload()">
		<div id="map" style="width:365px; height:200px"></div>
	</body>
</html>

Open in new window

LVL 1
movieprodwAsked:
Who is Participating?
 
Ray PaseurConnect With a Mentor Commented:
Here is the IFRAME that was generated (edited for readabiilty).  It looks like a data-dependent error, possibly in the code snippet at the original post in lines 72 ~ 87, but I'm not sure what data is getting sent into that part of the code.

To debug this, I would try dumping out that information BEFORE it goes into the processing near line 82.  You can use var_dump() to see the contents of $_GET -- that might be helpful.

Also on line 83, I think you might want explode() instead of split()...

$a2 = explode(",", $_GET["a2"]);

<iframe 
   src="gmap.php?a=r+Sunnyside+Dr%2C+asd%2C+AZ+85259&lat=0&lng=0&margin=8" 
   frameborder="0" 
   scrolling="no" 
   width="365" 
   height="200">
</iframe>

Open in new window

0
 
NerdsOfTechTechnology ScientistCommented:
What is the input field name for the ZIP? Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <STYLE type=text/css>
   BODY {
    MARGIN: 0px; 
    BACKGROUND-COLOR: #ffffff;
    font-family:Verdana, Arial, Helvetica, sans-serif;
    font-size:10px;
   }
  </STYLE>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <title>Google Map</title>
  <script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=ABQIAAAANy3TVrsW5WpnNvimGWqO-hQS_tGb29H7YG-S9HZO4R09DIw8tBTpAIwwit7hyJMO07C-IEjpbTLQpA" type="text/javascript"></script>
<script type="text/javascript">
 
var map = null;
var geocoder = null;
 
function load() {
 if (GBrowserIsCompatible()) {
  map = new GMap2(document.getElementById("map"));
  map.setMapType(G_PHYSICAL_MAP);
  map.setCenter(new GLatLng(37.4419, -122.1419), 13);
  geocoder = new GClientGeocoder();
 }
}
 
function showAddress(address, address2, dispaddress, lat, lng, bRetried) {
 if (geocoder) {
  geocoder.getLatLng(
  address,
  function(point) {
   if (!point) {
    if (bRetried){
     alert(address + " not found");
    }
    else{
     showAddress(address, address2, dispaddress, lat, lng, 1);                      
    }
   } else {
 
   var dIconConstructor = new GIcon();
   dIconConstructor.image = 'imagesmain/gmapicon.png';
   //  dIconConstructor.shadow = 'images/SS-GMap-Icon-5-shadow.png';
   dIconConstructor.iconSize = new GSize(35, 40.0);
   dIconConstructor.shadowSize = new GSize(80.0, 51.0);
   dIconConstructor.iconAnchor = new GPoint(20, 32.0);
   //  dIconConstructor.infoWindowAnchor = new GPoint(55.0, 4.0);
   var dIcon = new GIcon(dIconConstructor);
 
   map.addControl(new GSmallMapControl());
   //map.addControl(new GMapTypeControl());
   map.setCenter(point, 13);
   
   var marker = new GMarker(point, dIcon);
   map.addOverlay(marker);                  
   }
  }
  );
 }
}
        
function searchAddr() {
 <?
  if ($_GET["margin"]) {
   $sDisplay = "<div style='margin:".$_GET["margin"]."px'>".$_GET["d"]."</div>";
  }
  else {
   $sDisplay = $_GET["d"];
  }
  if (!$_GET["a2"]) {
   $a2 = split(",", $_GET["a2"]);
   $_GET["a2"] = $a2[0];
  }
 ?>
   showAddress("<?=$_GET["a"]?>","<?=$_GET["a2"]?>","<?=$sDisplay?>","<?=$_GET["lat"]?>","<?=$_GET["lng"]?>", 0);
 }
</script>
</head>
 
<body onload="load(); searchAddr();" onunload="GUnload()">
 <div id="map" style="width:365px; height:200px"></div>
</body>
</html>

Open in new window

0
 
movieprodwAuthor Commented:
This is the code I am using to load it.
<iframe src="gmap.php?a=<?php echo urlencode($street_address); ?>%2C+<?php echo  $city; ?>%2C+<?php echo  $state; ?>+<?php echo  $zip; ?>&lat=0&lng=0&margin=8" frameborder="0" scrolling="no" width="365" height="200"></iframe>

Open in new window

0
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

 
Ray PaseurCommented:
Can you show us what that IFRAME code generates when the script fails?

Here is a Geocoder class that I have used successfully.  You might be able to adapt it to your needs and then instead of sending all or part of an address, you could just send the Lat/Lon pair.
<?php // RAY_geocoder.php
 
// API KEYS, ETC.
require_once('_config.php');
 
// A FREEFORM LOCATION STATEMENT IS OPTIONAL (BUT NOT USED HERE)
$location = '';
if (!empty($_GET)) {
	foreach ($_GET as $k => $v) { $$k = get_clean_text_string($v); }
	if ($a != '') { $location .= $a . ' '; }
	if ($c != '') { $location .= $c . ' '; }
	if ($s != '') { $location .= $s . ' '; }
	if ($z != '') { $location .= $z . ' '; }
	$location = trim($location);
}
 
?>
<html><head><title><?=$a?> <?=$c?> <?=$s?> <?=$z?> Yahoo/Google Geocoder Query</title></head>
<body>
<form method="get">
Addr: <input type="text" name="a" autocomplete="off" value="<?=$a?>" />
City: <input type="text" name="c" autocomplete="off" value="<?=$c?>" />
ST:   <input type="text" name="s" autocomplete="off" value="<?=$s?>" size="2" />
Zip:  <input type="text" name="z" autocomplete="off" value="<?=$z?>" size="8" />
<input type="submit" name="_go" value="go" />
</form>
</body>
</html>
<?php
 
if (empty($_GET)) { die(); }
 
 
error_reporting(E_ALL);
 
 
// PREPARE THE GEOCODER
$y_demo			= new SimpleGeoCoder;
$y_demo->address	= $a;
$y_demo->city		= $c;
$y_demo->state		= $s;
$y_demo->zip		= $z;
 
// TEST THE YAHOO! GEOCODER
$y_demo->YahooGeoCode();
echo "<pre>\n\nYAHOO! ";
print_r($y_demo);
echo "</pre>\n";
 
 
// PREPARE THE GEOCODER
$g_demo			= new SimpleGeoCoder;
$g_demo->address	= $a;
$g_demo->city		= $c;
$g_demo->state		= $s;
$g_demo->zip		= $z;
 
 
// TEST THE GOOGLE GEOCODER
$g_demo->GoogleGeoCode();
echo "<pre>\n\nGOOGLE ";
print_r($g_demo);
echo "</pre>\n";
 
 
// ALL DONE
die();
 
 
 
// SIMPLE GEOCODER CLASS
class SimpleGeoCoder
{
 
// DECLARE THE INPUT DATA
public $location; // USE THIS FOR A FREEFORM QUERY, OR USE THESE PARTS
public $address;
public $city;
public $state;
public $zip;
 
// DECLARE THE WORKING DATA
private $precis; // TEXTUAL PRECISION FROM YAHOO
private $yfp, $yahoo_url,  $y_buf, $ydata;
private $gfp, $google_url, $g_buf, $gdata;
 
// DECLARE THE OUTPUT DATA
public $latitude;
public $longitude;
public $precision;
public $warning;
public $geocoder;
 
// DECLARE THE CONSTRUCTOR
public function __construct()
{
	$this->latitude		= 0.0;
	$this->longitude	= 0.0;
	$this->precision	= FALSE; // WANT A VALUE OF 5 OR HIGHER, HIGHER IS BETTER
	$this->warning		= '';
	$this->geocoder		= '';
}
 
 
// DECLARE THE YAHOO! VERSION OF THE WORKHORSE
public function YahooGeoCode()
{
	$this->geocoder	= 'Yahoo!';
	$yahoo_url	= "http://local.yahooapis.com/MapsService/V1/geocode?&appid=" . YAHOO_API;
 
	if ($this->location != '') // YOU CAN ASK FOR A FREEFORM QUERY
	{
		$yahoo_url	.= "&location=" . urlencode($this->location);
	}
	else // YOU CAN ASK FOR INDIVIDUAL PIECES OF AN ADDRESS
	{
		$yahoo_url	.= "&street=" . urlencode($this->address);
		$yahoo_url	.= "&city="   . urlencode($this->city);
		$yahoo_url	.= "&state="  . urlencode($this->state);
		$yahoo_url	.= "&zip="    . urlencode($this->zip);
	}
 
// EXECUTE YAHOO GEOCODER QUERY
// NOTE - USE ERROR SUPPRESSION OR IT WILL BARF UP THE YAHOO API - ON FAILURE RETURNS HTTP 400 BAD REQUEST
	if ($yfp = @fopen($yahoo_url, 'r'))
	{
		$y_buf	= '';
		while (!feof($yfp)) { $y_buf .= fgets($yfp); }
		fclose($yfp);
	}
	else
	{
		return FALSE;
	}
 
// EXAMINE THE RESULT
	if ($y_buf != '') // NOT EMPTY, WE GOT DATA
	{
		$ydata	= new SimpleXMLElement($y_buf);
 
// CHECK FOR ANY ERROR MESSAGE, IF NONE, EXTRACT THE DATA POINTS
		$y_err	= $ydata->Message;
		if ($y_err == '')
		{
			$this->precis		= $ydata->Result["precision"];
			$this->warning		= $ydata->Result["warning"];
			$this->latitude		= $ydata->Result->Latitude;
			$this->longitude	= $ydata->Result->Longitude;
			$this->address		= $ydata->Result->Address;
			$this->city		= $ydata->Result->City;
			$this->state		= $ydata->Result->State;
			$this->zip		= $ydata->Result->Zip;
 
// SET PRECISION TO A NUMBER VALUE
			if ($this->precis == 'zip')	{ $this->precision = "5"; }
			if ($this->precis == 'street')	{ $this->precision = "6"; }
			if ($this->precis == 'address')	{ $this->precision = "8"; }
		}
		else
		{
			return FALSE;
		}
	}
	else  // NO RESULT - SOMETHING IS SICK AT YAHOO
	{
		return FALSE;
	}
return TRUE;
} // END function YahooGeocode
 
 
// DECLARE THE GOOGLE VERSION OF THE WORKHORSE
public function GoogleGeoCode()
{
	$this->geocoder	= 'Google';
	$google_url	= "http://maps.google.com/maps/geo?key=" . GOOGLE_API . "&output=csv";
 
	if ($this->location != '') // YOU CAN ASK FOR A FREEFORM QUERY
	{
		$google_url	.= "&q=" . urlencode($this->location);
	}
	else // YOU CAN ASK FOR INDIVIDUAL PIECES OF AN ADDRESS
	{
		$google_url	.= "&q=" . urlencode(trim($this->address .' '. $this->city .' '. $this->state .' '. $this->zip));
	}
 
// EXECUTE GOOGLE GEOCODER QUERY
	if ($gfp = @fopen($google_url, 'r'))
	{
		$g_buf = '';
		while (!feof($gfp)) { $g_buf .= fgets($gfp); }
		fclose($gfp);
	}
	else
	{
		return FALSE;
	}
 
// EXTRACT THE DATA
	$gdata	= explode(',',$g_buf);
	if ($gdata[0] != '200') // RESPONSE CODE SHOULD BE '200' -- IF 602 - BAD ZIP CODE OR UNUSABLE ADDRESS
	{
		return FALSE;
	}
	$this->precision	= $gdata[1]; // GEOCODE ACCURACY - ZIP CODE = 5, HIGHER NUMBERS ARE BETTER
	$this->latitude		= $gdata[2];
	$this->longitude	= $gdata[3];
return TRUE;
} // END function GoogleGeocode
 
 
} // END class SimpleGeocoder

Open in new window

0
 
movieprodwAuthor Commented:
Hello Ray,

When it fails it just says that the address could not be found and it shows the standard ca map:

http://tinyurl.com/cs2p5j

Matt
0
 
movieprodwAuthor Commented:
Ok, thanks Ray!
0
 
movieprodwAuthor Commented:
Thanks Ray
0
 
Ray PaseurCommented:
Thanks for the points.  I expect when you get a clean address or part of an address into the IFRAME SRC= URL you'll get a better answer.  FWIW I have found the Google Maps to be quite "creative" when they are given partial addresses - in short, they make things up and you can find your map pointing to Armenia or the North Sea.  

If you can, get the best accuracy on the following fields, shown in priority order.  This is based on my work with USA and Canada geocoding.

COUNTRY
ZIP / POSTAL CODE
STATE or PROVINCE
CITY
STREET
STREET ADDRESS NUMBER or INTERSECTION

Best regards and good luck with your project, ~Ray
0
All Courses

From novice to tech pro — start learning today.