How to get lat long from address in WordPress
Sometimes in wordpress we need to get latitude and longitude of a specific location from a address. Actually sometimes it is required to show location map, to get exact position of a particular place or we can use it to get the postal code for that location. As we know the coordinates are the basic information for a location.
To get the lat long for a location we need to follow the following steps :
Step 1 : Put the below mentioned code in functions.php of your current theme :
function get_lat_long($address){ $address = str_replace(" ", "+", $address); $json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region"); $json = json_decode($json); $lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'}; $long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'}; return $lat.','.$long; }
Step 2. Just copy and paste the below mentioned code at the place where you want to get the lat long information for a given address :
$address = "Jawahar Circle, Jaipur, Rajasthan, India"; //put your address here $latlong = get_lat_long($address); $latlong = explode(',' ,$latlong); $lat = $latlong[0]; //latitude value for mentioned address $long = $latlong[1]; //longitude value for mentioned address echo "Latitude is : ".$lat." and Longitude is : ".$long." for given Address : ".$address;
Follow the above two steps and you will get the lat long information for a given address in few minutes. Modify the code as per your use and stay in touch with us to get best wordpress tricks.
Ty, it helps me, but you have an error for a copy/paste, you define the function’s name “calculate_lat_long” and you use “get_lag_long” 😉
I am glad it helped you…I really appreciate your input…I have rectified the error.
Thanks 🙂
Thanks really very helpful… it worked for me… Thank You
What is $region for? It is not defined anywhere but used in the API call
It is an optional parameter in API call. If you want to find values for a specific region you can define it above, other wise it will work for all regions.
stdClass Object
(
[error_message] => You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account
[results] => Array
(
)
[status] => REQUEST_DENIED
)
How to make it so that it shows the location of the user and shows the nearest custom posts that already have the specified location?