How to get latitude and longitude from google map using Codeigniter
In this article, you’ll know how to get latitude and longitude from address using Google Maps API in Codeigniter. Here we’ll combine all code into a Codeigniter function and you only need to use this function to find latitude and longitude from an address.
You can need first create API
https://maps.googleapis.com/maps/api/geocode/json?address=""&key=API_KEY
PHP Code
public function getlocation()
{
$address = "Katargam";
$city = "Surat";
$state = "Gujarat";
$array = $this->get_longitude_latitude($address,$city,$state);
$latitude = round($array['latitude'], 6);
$longitude = round($array['longitude'], 6);
}
function get_longitude_latitude($address, $cityname, $statename)
{
if ($address <> '')
{
$string = $address . " ".$cityname . " " . $statename;
}
else
{
$string = $cityname . " " . $statename;
}
$string = str_replace(" ", "+", urlencode($string));
$details_url = "https://maps.googleapis.com/maps/api/geocode/json?address=".$string."&key=";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
if ($response['status'] != 'OK') {
return null;
}
$geometry = $response['results'][0]['geometry'];
$longitude = $geometry['location']['lat'];
$latitude = $geometry['location']['lng'];
$array = array(
'latitude' => $geometry['location']['lat'],
'longitude' => $geometry['location']['lng'],
'location_type' => $geometry['location_type'],
);
return $array;
}
And if you like this tutorials please share it with your friends via Email or Social Media.
Leave a Reply