Geocoding in PHP Tutorial

Geocoding is a very important task this days to locate your customers as well as find addresses and which are properly formatted.
For this tutorial we have used Geokeo Geocoder Api. You can sign up for free and get 2500 api limit daily.



First we will learn how to forward geocode then reverse geocode then do the same with mysql.

Forward Geocoding in PHP


Forward geocoding is nothing but converting addresses to latitude and longitude

for eg- empire state building -> LAT-40.74843124430164 , LNG- -73.9856567114413
Formatted address- Empire State Building,Manhattan Island,Midtown South,5th Avenue,New York County,New York City,10018,United States Of America.

This can be used geolocate your customers to a known loaction and provide service as required. Find postal address and various many activities
<?php

$url = "https://geokeo.com/geocode/v1/search.php?q=".url_encode(empire state building)."&api=YOUR_API_KEY";

//call api
$json = file_get_contents($url);
$json = json_decode($json);
if(array_key_exists('status',$json))
{
	
	if($json->status=='ok')
	{
		$address = $json->results[0]->formatted_address;
		$latitude = $json->results[0]->geometry->location->lat;
		$longitude = $json->results[0]->geometry->location->lng;
		//do something with the data
			
	}		
}
?>

In the line $url = "https://geokeo.com/geocode/v1/search.php?q=".url_encode(empire state building)."&api=YOUR_API_KEY"
two parameters are used one is the string which is to be searched (empire state building) another is YOUR_API_KEY which can be available by login to geokeo.com and in the dashboard api section.
Responses are available in json and xml format. default is json format. for more information follow the documentation.



The result of the last query is

{
  "results": [
     {
      "class": "tourism",
      "type": "attraction",
      "address_components": {
        "name": "Empire State Building",
        "island": "Manhattan Island",
        "neighbourhood": "Midtown South",
        "street": "5th Avenue",
        "subdistrict": "Manhattan",
        "district": "New York County",
        "city": "New York City",
        "state": "New York",
        "postcode": "10018",
        "country": "United States Of America"
      },
      "formatted_address": "Empire State Building,Manhattan Island,Midtown South,5th Avenue,New York County,New York City,10018,United States Of America",
      "geometry": {
        "location": {
          "lat": "40.74843124430164",
          "lng": "-73.9856567114413"
        },
        "viewport": {
          "northeast": {
            "lat": "40.747922600363026",
            "lng": "-73.9864855"
          },
          "southwest": {
            "lat": "40.74894220036315",
            "lng": "-73.98482589999999"
          }
        }
      },
      "osmurl": "https://www.openstreetmap.org/search?query=40.74843124430164%2C-73.9856567114413#map=17/40.74843124430164/-73.9856567114413",
      
    }
  ],
  "credits": "https://geokeo.com/credits.php",
  "status": "ok"
}

The php function json_decode is used to iterate and extract all the relevant data. Further details of json decode can be found at Json Decode

Reverse Geocode in PHP


Reverse geocoding is just the opposite of forward geocoding- for eg- 40.74843124430164,-73.9856567114413 -> Formatted address- Empire State Building,Manhattan Island,Midtown South,5th Avenue,New York County,New York City,10018,United States Of America. This can be utilized to format addresses from data received from browser location or android devices etc.
<?php

$url = "https://geokeo.com/geocode/v1/reverse.php?lat=40.74842&lng=-73.9856&api=YOUR_API_KEY";

//call api
$json = file_get_contents($url);
$json = json_decode($json);
if(array_key_exists('status',$json))
{
	
	if($json->status=='ok')
	{
		$address = $json->results[0]->formatted_address;
		$latitude = $json->results[0]->geometry->location->lat;
		$longitude = $json->results[0]->geometry->location->lng;
		//do something with the data

			
	}		
}
?>
In the line $url = "https://geokeo.com/geocode/v1/reverse.php?lat=40.74842&lng=-73.9856&api=YOUR_API_KEY" three parameters are used one is the latitude which is to be searched (40.74842) another is longitude (-73.9856) and another is YOUR_API_KEY which can be available by login to geokeo.com and in the dashboard api section.

Responses are available in json and xml format. default is json format. for more information follow the

The result of the last query is

{
  "results": [
     {
      "class": "tourism",
      "type": "attraction",
      "address_components": {
        "name": "Empire State Building",
        "island": "Manhattan Island",
        "neighbourhood": "Midtown South",
        "street": "5th Avenue",
        "subdistrict": "Manhattan",
        "district": "New York County",
        "city": "New York City",
        "state": "New York",
        "postcode": "10018",
        "country": "United States Of America"
      },
      "formatted_address": "Empire State Building,Manhattan Island,Midtown South,5th Avenue,New York County,New York City,10018,United States Of America",
      "geometry": {
        "location": {
          "lat": "40.74843124430164",
          "lng": "-73.9856567114413"
        },
        "viewport": {
          "northeast": {
            "lat": "40.747922600363026",
            "lng": "-73.9864855"
          },
          "southwest": {
            "lat": "40.74894220036315",
            "lng": "-73.98482589999999"
          }
        }
      },
      "osmurl": "https://www.openstreetmap.org/search?query=40.74843124430164%2C-73.9856567114413#map=17/40.74843124430164/-73.9856567114413",
      "distance": "0.0010302984507433km"

      
    }
  ],
  "credits": "https://geokeo.com/credits.php",
  "status": "ok"
}

The php function json_decode is used to iterate and extract all the relevant data. Further details of json decode can be found at Json Decode
The extra result here is the distance which shows how far the actual co ordinates are from the available address in the database.

Forward geocoding in PHP with Mysql



Mysql is a very popular database which can be used to fetch data from database and feed to the above function to update your database.
<?php
$servername = "localhost";
$username = "username";  //change as per your username and password
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, address FROM addresses";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  
  while($row = $result->fetch_assoc()) {
   

$url = "https://geokeo.com/geocode/v1/search.php?q=".url_encode($row["address"])."&api=YOUR_API_KEY";

//call api
$json = file_get_contents($url);
$json = json_decode($json);
if(array_key_exists('status',$json))
{
	
	if($json->status=='ok')
	{
		$address = $json->results[0]->formatted_address;
		$latitude = $json->results[0]->geometry->location->lat;
		$longitude = $json->results[0]->geometry->location->lng;
		//do something with the data
		$conn->query("UPDATE addresses SET formattedaddress='$address',latitude='$lat',longitude='$lng' WHERE id=".$row["id"]);
              //This line will update your database with the latitude and longitude and 
	}		
}

  }
} else {
  echo "0 results";
}
$conn->close();
?>
This snippets of code can be utilized to convert your unformatted addresses into formatted addresses with proper latitude and longitude data.This method can be used to do bulk geocoding or batch geocoding.

Happy Geocoding

Team GEOKEO.