Kiran Dash
Kiran Dash

Reputation: 4956

Fetching lat lng values in a faster way using a php script

I have a script shown below which I am using to get lat and lng values of an address stored in a $address variable.

if(my condition here){  
    $prepAddr = urlencode($address);
    $geocode = file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false&key=myapikey');
    $output= json_decode($geocode);

    $address_lat = $output->results[0]->geometry->location->lat;
    $address_lng = $output->results[0]->geometry->location->lng;
}     

The script works totally fine. But the problem is I have more than a 1000 addresses that I have to loop through and create a csv result based on the data. When I do this it takes a really long time and always fails after generating results for 200 approx. items.

So how do I get the lat lng values in a php script in a faster way?

I did test to see if the delay was because of csv generation but no, if I replace the lat lng generation code above with static values for lat and lng then the csv is generated quicker(in < 10 sec or so). But with the file_get_contents it takes like 6 to 10 minutes.

So for sure the problem is with the way I am getting lat and lng values. I guess may be some one can let me know of a quicker way to get lat lng values using full address inside of a PHP script.

May be there is a way to include the javascript code inside the PHP script? I don't know how to do that though? And if that is going to be fast?

Upvotes: 0

Views: 100

Answers (2)

Rick
Rick

Reputation: 711

I'm not sure your need for accuracy, but you could use MaxMind's "Free World Cities Database".

And on that page there is another link to a "GeoNames" database that could also be useful.

Pending these databases will fill your needs you could then import the file data into a database and run queries through them to get your lat/lng much quicker (with some setup of course)..

Not saying this is the best option, just another option..

Upvotes: 1

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

The best way to achieve this is to create a function that fetch one address at a time and retrieve its lat, lng from google API and store it in the address table (add two additional column in address table for lat, lng and one more column to maintain the status of the address whose lat, lng are fetched)

Put this function on CRON on every seconds or what ever time is suitable for you. Now when you required the CSV, fetch the records from the table and make csv from it.

NOTE: There is a per second and day hit limit of google API, in case of your for loop the limit will reach for seconds after certain loops.

Upvotes: 1

Related Questions