Here, I am going to explain function which will return latitude and longitude value by passing address.
Google map provides great functionality to get latitude or longitude values using an address or you can get an address using latitude and longitude values.
Here I have called Google API and have passed address into URL. Before passing address into URL , I have encoded it with urlencode
function.
Next, I have called cURL which is used to get data or response from another server in PHP and you will get latitude and longitude values and use it whenever you want.
I have used the following code into WordPress but you can use code into any of your PHP coding structure with some modification.
After reading all this paragraphs, now it’s time for checking code.
So let’s understand following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | if(!function_exists('find_latitude_longitude_by_address')) { function find_latitude_longitude_by_address($address = "") { $address = urlencode($address); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXYPORT, 3128); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); curl_close($ch); $response_a = json_decode($response); if($response_a && isset($response_a->results) && isset($response_a->results[0]) && isset($response_a->results[0]->geometry->location->lat) && isset($response_a->results[0]->geometry->location->lng)) { $lat = $response_a->results[0]->geometry->location->lat; $long = $response_a->results[0]->geometry->location->lng; $formatted_address = $response_a->results[0]->formatted_address; $result = array($lat, $long, $formatted_address); return $result; } else { // default lat long for location. $result = array('lat', long', 'India'); return $result; } } } |
I hope you get this function and if you have any query, post your comments below. You can modify this function as per your requirement and use it.
Also Read:
Fetch Twitter data with cURL
To read JSON data with jQuery
Hope this article helps someone.As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.