Hello what is the formulla to get longitude and latitude of any address , if i have street_name,State_name,City_name,Country_name and zip code in PHP? Thanks
-
Hi Ajay - I think you mean "longitude" – Paddyslacker Sep 27 '10 at 21:18
-
6possible duplicate of [How to obtain longitude and latitude for a street address programmatically (and legally)](http://stackoverflow.com/questions/158474/how-to-obtain-longitude-and-latitude-for-a-street-address-programmatically-and-l) – jball Sep 27 '10 at 21:20
-
To clarify, there is no formula, but companies do provide geocoding services. See the above linked "dupe". – jball Sep 27 '10 at 21:22
7 Answers
Use the following code for getting lat and long using php. Here are two methods:
Type-1:
<?php
// Get lat and long by address
$address = $dlocation; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
?>
edit - Google Maps requests must be over https
Type-2:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(50.804400, -1.147250);
var mapOptions = {
zoom: 6,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
}
function codeAddress(address,tutorname,url,distance,prise,postcode) {
var address = address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
});
infowindow.open(map,marker);
} /*else {
alert('Geocode was not successful for the following reason: ' + status);
}*/
});
}
google.maps.event.addDomListener(window, 'load', initialize);
window.onload = function(){
initialize();
// your code here
<?php foreach($addr as $add) {
?>
codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
<?php } ?>
};
</script>
<div id="map-canvas12"></div>

- 56,955
- 33
- 144
- 158

- 1,512
- 2
- 24
- 38
-
That's exactly what I was looking for. Thank you! May I ask something? I need this functionality only for internal calculations. The API documentation explicitly says that the API may only be used in conjunction of the Google Maps service. Is your code example in this condition? – C-H-a-P Jun 14 '13 at 15:32
-
In type 1, I am getting "You have exceeded your daily request quota for this API." as error message after a few tests ... any workaround for not getting the daily request quota ? – Jeremy Feb 03 '15 at 09:36
-
3Need to add "&key=API_KEY" to the end of the URL in the PHP example above, otherwise you'll likely run in to issues with exceeding the quota. e.g. https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY More on it here: https://developers.google.com/maps/documentation/geocoding/ – Henry Weber Mar 07 '15 at 00:29
-
Make sure to add `https://` on php version of the `file_get_contents` line or it will return `Array ( [error_message] => Requests to this API must be over SSL. Load the API with "https://" instead of "http://". [results] => Array ( ) [status] => REQUEST_DENIED ) NULL ` – dale landry Apr 29 '17 at 06:30
-
1Wouldn't urlencode() be better to prepare the address since a "&" would mess everything up, instead of just replacing spaces with "+"? – NaturalBornCamper Jul 31 '17 at 10:22
-
Note that you will need to supply a Google Geocoding API key in the querystring (remember to Enable billing), e.g. https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false&key=API_KEY_HERE – Starjumper Tech SL Mar 23 '19 at 12:18
<?php
$address = 'BTM 2nd Stage, Bengaluru, Karnataka 560076'; // Address
$apiKey = 'api-key'; // Google maps now requires an API key.
// Get JSON results from this request
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.$apiKey);
$geo = json_decode($geo, true); // Convert the JSON to an array
if (isset($geo['status']) && ($geo['status'] == 'OK')) {
$latitude = $geo['results'][0]['geometry']['location']['lat']; // Latitude
$longitude = $geo['results'][0]['geometry']['location']['lng']; // Longitude
}
?>

- 3,093
- 1
- 13
- 26

- 10,556
- 10
- 48
- 77
-
1Just for others, if you're not able to retrieve them, print_r the $geo variable to see the error happening. For me, I had to use an API key, specified in the query with (&key=[API_KEY]) and https. – Richi González Jun 12 '19 at 20:51
-
You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.

- 1,953
- 2
- 17
- 35
You can use the Google Maps API for that. See the blog post below for more information.
http://stuff.nekhbet.ro/2008/12/12/how-to-get-coordinates-for-a-given-address-using-php.html

- 3,743
- 1
- 25
- 41
PHP has some nice built in functions for getting geographic location. Maybe have a look here: http://php.net/manual/en/ref.geoip.php
According to php manual, "This extension requires the GeoIP C library version 1.4.0 or higher to be installed. You can grab the latest version from » http://www.maxmind.com/app/c and compile it yourself."

- 2,041
- 1
- 18
- 24
I came up with the following which takes account of rubbish passed in and file_get_contents failing....
function get_lonlat( $addr ) {
try {
$coordinates = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($addr) . '&sensor=true');
$e=json_decode($coordinates);
// call to google api failed so has ZERO_RESULTS -- i.e. rubbish address...
if ( isset($e->status)) { if ( $e->status == 'ZERO_RESULTS' ) {echo '1:'; $err_res=true; } else {echo '2:'; $err_res=false; } } else { echo '3:'; $err_res=false; }
// $coordinates is false if file_get_contents has failed so create a blank array with Longitude/Latitude.
if ( $coordinates == false || $err_res == true ) {
$a = array( 'lat'=>0,'lng'=>0);
$coordinates = new stdClass();
foreach ( $a as $key => $value)
{
$coordinates->$key = $value;
}
} else {
// call to google ok so just return longitude/latitude.
$coordinates = $e;
$coordinates = $coordinates->results[0]->geometry->location;
}
return $coordinates;
}
catch (Exception $e) {
}
then to get the cords: where $pc is the postcode or address.... $address = get_lonlat( $pc ); $l1 = $address->lat; $l2 = $address->lng;

- 900
- 2
- 9
- 19
There is no forumula, as street names and cities are essentially handed out randomly. The address needs to be looked up in a database. Alternatively, you can look up a zip code in a database for the region that the zip code is for.
You didn't mention a country, so I'm going to assume you just want addresses in the USA. There are numerous databases you can use, some free, some not.
You can also use the Google Maps API to have them look up an address in their database for you. That is probably the easiest solution, but requires your application to have a working internet connection at all times.

- 4,079
- 3
- 22
- 33