Geocoder.us API
Another solution to get latitudes and longitudes for US addresses is geocoder.us. They also have some web APIs to call this service online. Full help files are available here.
You can choose from a few solutions: XML-RPC, SOAP, REST or even RDF or CSV. All of them are ok, as long as they works for you. I'll show you here two solutions: SOAP & CVS, one server side with PHP, the latter client side with XMLHTTPRequest and CVS.
Entry point pages are:
http://geocoder.us/service/xmlrpc
http://geocoder.us/service/soap
http://geocoder.us/service/rest/geocode
http://geocoder.us/service/csv/geocode
Here's PHP sample:
<?php
if($_POST['addr']!='') {
include 'nusoap.php';
$soapclient = new soapclient('http://geocoder.us/service/soap');
$results = $soapclient->call('geocode',array($_POST['addr']));
if(is_array($results))
echo "Latitude: {$results[0]['lat']} -
Longitude: {$results[0]['long']}";
}
?>
<form method=post name=frmgeous >
Address: <input name=addr>
<input type=submit value=Submit name=submit>
</form>
This page is very basic: just display a form with a text-box for full address and a submit button. When clicked, values are passed to the server, interogating Geocoder.us and display results, if returned. This sample also uses Nusoap.php.
Client-side we can use only JavaScript to achieve the same results. Just add in the form above a simple button that call JavaScript function from a separate include file (uses the same text-box for address), before closing form tag:
<script language="JavaScript" src="/geocoder.us.js" mce_src="/geocoder.us.js" ></script>
<input type=button value=JavaScript onclick="javascript:geocode_us();">
Here's the JavaScript code, available for download:
function geocode_us() {
var xmlhttp=null;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}if(xmlhttp) {
xmlhttp.open("GET", "./load.php?url="+
escape("geocoder.us/service/csv/geocode?address="+
document.forms['frmgeous'].addr.value), false);
xmlhttp.send("");
arr=xmlhttp.responseText.split(',');
alert('Latitude: '+arr[0]+'\nLongitude: '+arr[1]);
}
}
This uses the same loader (load.php) to overcome security limits when accessing pages from another domain, client-side. It uses XMLHTTPRequest() on Firefox and ActiveX XML for IE when interrogating Geocoder.us server. See it at work:
For commercial requests see their website for prices and terms. This is also simple, isn't it?