Get Latitude and Longitude from address using PHP

Here is a simple function i build to get latitude and longitude. You just need to pass your address in this function parameter and it will return you the latitude and longitude of given address.

Usage example of this function are given below :


function GetLatLngFromAddress($address) {
 $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false&key=AIzaSyBWcIbvlItoTmvdlkgY-7DOLiTwmDTTYHE";
 
 // Make the HTTP request
 $data = @file_get_contents($url);
 
 // Parse the json response 
 $jsondata = json_decode($data,true);

 // If the json data is invalid, return empty array 
 if ($jsondata["status"] == "OK"){
  $LatLng = array(

   'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"],

   'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"],

  );
  return $LatLng;
    } else {
  return array( "error"=>$jsondata["status"] ) ;
    }
}



How to use :

You just need to pass the address in the above function and it will return you the address like below-


$address = "1600+Amphitheatre+Parkway,+Mountain+View,+CA"; //Pass your address here

$sample = GetLatLngFromAddress($address);

echo "Adress: $address <BR />";

echo "The latitude of the above address is " . $sample['lat'] . " and longitude is " . $sample['lng'];


If you like this post please don't forgot to notify me to post a comment .

Happy Coding :)

Post a Comment

Previous Post Next Post