I am having multiple addresses saved to my database. I want to fetch the longitude and latitude of multiple addresses. I am usng the code :
foreach($address as $addr)
{
$prepAddr = str_replace(' ','+',$addr);
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
echo $latitude = $output->results[0]->geometry->location->lat;
echo $longitude = $output->results[0]->geometry->location->lng;
}
$address is array in which all the addresses are returned.
The problem is that as the addresses are above 500, so the page takes long to load. I have refered to the links How to get longitude latitude of multiple addresses geo-location
But, can't get this to work.
Please can you help me. Any help is really appreciated.
I would suggest that the delay is more todo with the time it takes to connect to the api and get data back, rather than the speed of the loop itself.
To make this more scaleable, how about you look at how many addresses it works okay with, then process them in batches. If it works with 100 okay, then load it with start=100
, and the end of the run, have the script call itself again with start=$start+100
until there are none left.
First of all Use the foreach instead of for loop as it is faster.
Second thing is use the CURL instead of file_get_content as curl is faster than this as I have seen in the discussion of SO.
Check this link: using file get contents or curl
You can use the curl here is the sample code of curl:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, trim($request));
$result = curl_exec($ch);
curl_close($ch);
This will surely reduce the time of execution.