I have written the following function in php to geocode a customers' address from the MapQuest API. I know that google is far better, but I need to use this for a commercial project and want to use a free solution.
I am getting results for about 40-50% of addresses I try to geocode. (I have tried about 20 so far). (I haven't verified the results of the accuracy of the addresses, just the fact that I got a result).
Is there any way I can improve the geocoding results using their API. I don't want to share addresses as that is private information, but for all the addresses I supply all the parameters except country and address_2.
function geocode_customer($customer_id)
{
$customer_info = $this->get_info($customer_id);
$mapquest_api_key = 'MY%API%KEY';
$geocode_base_api_url = 'http://open.mapquestapi.com/geocoding/v1/address';
$params = array();
$params['key'] = $mapquest_api_key;
$params['outFormat'] = 'json';
if ($customer_info->country)
{
$params['country'] = $customer_info->country;
}
if ($customer_info->state)
{
$params['state'] = $customer_info->state;
}
if ($customer_info->zip)
{
$params['postalCode'] = $customer_info->zip;
}
if ($customer_info->city)
{
$params['city'] = $customer_info->city;
}
if ($customer_info->address_1)
{
$street = $customer_info->address_1;
if ($customer_info->address_2)
{
$street.= ' '.$customer_info->address_2;
}
$params['street'] = $street ;
}
$params['format'] = 'json';
$params_string = '';
//url-ify the data for the POST
foreach($params as $key=>$value)
{
$value = $key == 'key' ? $value : rawurlencode($value);
$params_string .= $key.'='.$value.'&';
}
$params_string = rtrim($params_string, '&');
$api_url = $geocode_base_api_url.'?'.$params_string;
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $api_url);
$contents = curl_exec($c);
curl_close($c);
$resp = json_decode($contents, true);
if(!empty($resp['results'][0]['locations']))
{
$latLng = $resp['results'][0]['locations'][0]['latLng'];
return $latLng['lat'].','.$latLng['lng'];
}
//Default to Denver CO
return '39.737567,-104.9847179';
}
Copyright Notice:Content Author:「Chris Muench」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/21868673/improving-geocoding-accuracy-using-mapquest-open-data