我在php中编写了以下函数,以便从MapQuest API对客户的地址进行地理编码。我知道谷歌要好得多,但我需要将它用于商业项目,并希望使用免费的解决方案。
我得到了大约40-50%的地址我试图进行地理编码的结果。 (到目前为止,我已经尝试了大约20个)。 (我没有验证地址准确性的结果,只是我得到了一个结果)。
我有什么方法可以使用他们的API来改善地理编码结果。我不想共享地址,因为这是私人信息,但对于所有地址,我提供除country和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';
}