This topic is locked

Google MAP RESTful API service -Geocoding API-

5/25/2020 5:13:15 AM
PHPRunner Tips and Tricks
fhumanes author


Google has a very extensive set of APIs that offer extraordinary services to applications.
Specifically, what I want to tell you this time is something that in my professional life has always been a goal, but that I had never managed to solve easily.
Whenever we work with people (clients, patients, suppliers, etc.) we always use an identification element that is the postal address (the address).
If you talk to the staff who run the GIS in your organization, they will tell you that an address requires a wide set of fields (street type, street name, number or KM, etc.), making it very difficult to collect this data. Until recently, all of this data was necessary to obtain latitude and longitude (X,Y) and represent that address on a map. In addition, latitude and longitude (X,Y) is used to calculate distances between two places and many other functions.
In this example that I leave you, my requirements were:

  • A customer's mailing address is provided and the system must provide me with a standard (complete) address and its latitude and longitude, to place it on a map.
  • Represent clients on a map.
  • Decide which store should provide (by proximity) the products to the customer.


Point (3) is easily solved by applying the Pythagorean theorem. The distance is the Hypotenuse and the catetos are the differences of the X and Y coordinates, between the customer and the store. That difference that is smaller means that this store is the closest to the customer.
To use Google Map services it is necessary:

  • Have a Gmail account.
  • Connect to the Google services management tool. https://console.cloud.google.com/
  • Define the services:
  • Geocoding API .- To validate addresses and obtain the latitude and longitude of the address.
  • Maps JavaScript API.- To show maps with references.
  • For these services to work, you have to provide Google with your billing information, specifically your credit card. Google gives you $300 to deduct from your billing for the year and indicates that it will not bill you until you authorize it to do so. Those 300 dollars, indicates that they are more than enough for low traffic web with Google Map. And that if you do business with your blog or application, they want some of the benefit to come to them for the service they provide. In principle, we should not be "afraid" to provide them with this information.


DEMO: https://fhumanes.com/streetmap
(It will be a short time, since I do not want to consume the $300 with this demo)


(1) Address that was delivered to the system

(2) Address obtained from Google Map

(3) Store assigned by Proximity


(1) Map of defined location

(2) Latitude and Longitude calculated by Google Map
Technical Solution
The presentation of maps, I have used the standard way that PHPrunner have to present maps from Google Map, Maps Javascript Api service.
For the validation of the address I have used theGeocoding API service. There are multiple ways to use this service in the PHP language, but as with version 10.4 of PHPRunner "RESTfull API services have become fashionable", I have used it with this interface.
As it is in an event where I have to execute the service, I have done it outside of the PHPRunner solution (I don't know if it could be done directly) and to make the request I have used the PHP libraryunirest 3.0.4, which I have already used it on other occasions for the RESTfull API services.
I am attaching some of the most interesting codes:
find_street.php.- Search for the normalized address and X, Y coordinates of Customers and Stores.



<?php

// Validate postal address and obtain the latitude and longitude of the address

function valueToZero($val){

return empty($val)?0:$val;

}

@ini_set("display_errors","1");

@ini_set("display_startup_errors","1");

require_once __DIR__ . '/../unirest_3.0.4/autoload.php';

$url_basic = 'https://maps.googleapis.com/maps/api/geocode/json';

$host = 'maps.googleapis.com';

$api_key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaa'; // Your Api Key of Google MAP

$lang='es'; // For services of Google Map

$address = $values['address'];

$address = str_replace("\n", ',', $address);

$address = str_replace("\r", ' ', $address);

$address = htmlspecialchars($address);

$response = Unirest\Request::get("$url_basic?address=$address&language=$lang&key=$api_key",

array()

);

$a = $response->code; // HTTP Status code

$b = $response->headers; // Headers

$c = $response->body; // Parsed body

$d = $response->raw_body; // Unparsed body

$f = json_decode($d,true);

// var_dump($f); // DUMP pf array

$count = count($f["results"]);

foreach($f["results"] as $results) {

$standardAddress = $results["formatted_address"];

$latency = $results["geometry"]["location"]["lat"];

$length = $results["geometry"]["location"]["lng"];

$dir = array();

foreach($results["address_components"] as $e) {

$type = $e["types"][0];

$dir[$type] = $e["long_name"];

}

$standardAddress2 = $dir["route"].', '.$dir["street_number"].' '.$dir["subpremise"]."\n".

$dir["postal_code"].' '. $dir["locality"]."\n".

$dir["administrative_area_level_2"]."\n".

$dir["administrative_area_level_1"]."\n".

$dir["country"];

$values["standardAddress"] = $standardAddress2;

$values["latency"] = $latency;

$values["length"] = $length;

break;

}


find_store.php .- Search for the store closest to the customer.



<?php

// Find the store closest to the Customer

$customer = $values['idclient'];

// Pythagoras theorem | The square of the hypotenuse is equal to the sum of the square of its lengths of the triangle's other two sides.

$sql="

SELECT idclient, ((s.`latency`-c.`latency`)*(s.`latency`-c.`latency`))+((s.`length`-c.`length`)*(s.`length`-c.`length`)) d, s.`idstore`

FROM streetmap_client c

join streetmap_store s

where idclient = $customer

order by 2

";

$resql=db_query($sql,$conn);

$row=db_fetch_array($resql);

$store = $row['idstore'];

$sql="update streetmap_client set `streetmap_store_idstore` = $store where `idclient` = $customer";

$resql=db_query($sql,$conn);


Example of the response JSON of a Geocoding request



{

"results": [

{

"access_points": [],

"address_components": [

{

"long_name": "4º",

"short_name": "4º",

"types": [

"subpremise"

]

},

{

"long_name": "1",

"short_name": "1",

"types": [

"street_number"

]

},

{

"long_name": "Plaza Puerta del Vado",

"short_name": "Plaza Puerta del Vado",

"types": [

"route"

]

},

{

"long_name": "Alcalá de Henares",

"short_name": "Alcalá de Henares",

"types": [

"locality",

"political"

]

},

{

"long_name": "Madrid",

"short_name": "M",

"types": [

"administrative_area_level_2",

"political"

]

},

{

"long_name": "Comunidad de Madrid",

"short_name": "Comunidad de Madrid",

"types": [

"administrative_area_level_1",

"political"

]

},

{

"long_name": "España",

"short_name": "ES",

"types": [

"country",

"political"

]

},

{

"long_name": "28803",

"short_name": "28803",

"types": [

"postal_code"

]

}

],

"formatted_address": "Plaza Puerta del Vado, 1, 4º, 28803 Alcalá de Henares, Madrid, España",

"geometry": {

"location": {

"lat": 40.4775031,

"lng": -3.3672253

},

"location_type": "ROOFTOP",

"viewport": {

"northeast": {

"lat": 40.4788520802915,

"lng": -3.365876319708498

},

"southwest": {

"lat": 40.4761541197085,

"lng": -3.368574280291502

}

}

},

"partial_match": true,

"place_id": "EkZQbGF6YSBQdWVydGEgZGVsIFZhZG8sIDEsIDTCuiwgMjg4MDMgQWxjYWzDoSBkZSBIZW5hcmVzLCBNYWRyaWQsIFNwYWluIh8aHQoWChQKEgnbObgHEUlCDREUmIaYMumwmRIDNMK6",

"types": [

"subpremise"

]

}

],

"status": "OK"

}


As usual I leave the project code on my blog so that you can install it on your computers, but first, you must put the Google MAP “Key API”, so that it works for you.
For any questions or what you need, use my email account [email="fernandohumanes@gmail.com"]fernandohumanes@gmail.com[/email]

admin 5/25/2020

It would be nice to see some screenshots that explain what this project actually does.

fhumanes author 5/25/2020



It would be nice to see some screenshots that explain what this project actually does.



Thank you.
I have already put some pictures.
Cheers,

fernando