Wednesday, 14 August 2013

Trying to get Google coords with PHP .. timing out?

Trying to get Google coords with PHP .. timing out?

I'm trying to get Google lat and long from a user entered address. I would
like to do this before database insertion, but maybe there is a better
way?
When I run this function as a standalone, it works and returns coordinates
$addressString = "21 Albert St Montreal H2W2H1";
function get_google($addressString){
if (!is_string($addressString))die("All Addresses must be passed
as a string");
$_url =
sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($addressString));
$_result = false;
if($_result = file_get_contents($_url)) {
if(strpos($_result,'errortips') > 1 || strpos($_result,'Did
you mean:') !== false) return false;
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U',
$_result, $_match);
$_coords['lat'] = $_match[1];
$_coords['long'] = $_match[2];
}
echo $_coords['lat'] . " " . $coords['long']; // echoes correctly
}
.. but when I try this in my code it seems to only return NULL for those
values. (I'm using Codeigniter)
$data->name = $this->input->post('name');
$data->address = $this->input->post('address');
$coords = $this->get_google($data->address);
$data->goog_lat = $coords[0]; // seems to be returning NULL
$data->goog_long = $coords[1]; // and i get 'undefined offset' errors
(because of NULL, i guess?)
$this->client_model->add_client($data);
.. so when I try that I am not getting Google coordinates.. only NULL values.
Can anyone tell me what I am screwing up, or a better way to do this? Is
this because of some timing issue or is it something else?

No comments:

Post a Comment