Matteo Bandiera

Web Developer

Wordpress configuration

WordPress, from address to longitude – latitude using Google Maps API

- by

What is Geocoding?

The Google Maps Geocoding API allows us to convert addresses ( like “34 Apt, Horizon Building, Royal Canal Park, Dublin15”) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which we can use, for example, to place markers on a map.
 

Google Maps Geocoding API Request Format

A Google Maps Geocoding API request must be of the following form:

https://maps.googleapis.com/maps/api/geocode/output?parameters

where output may be either of the following values:

  • json (recommended) indicates output in JavaScript Object Notation (JSON)
  • xml indicates output as XML

Some parameters are required while some are optional. As is standard in URLs, parameters are separated using the ampersand (&) character.

 

Required parameters in a geocoding request:

  • address — The street address that you want to geocode.
    or
    components — A component filter for which you wish to obtain a geocode.
  • key — Your application’s API key.

For more information you can refer to the Google Maps Geocoding API page.

 

How can we implement and HTTP get request to the Google Maps API in WordPress?

A quick example.


function mb_geocoding( $address ) {
  // encode address coming from your form
  $address = urlencode( $address );
  $api_endpoint = "http://maps.google.com/maps/api/geocode/json?address={$address}&key=YOUR_API_KEY";
	
  // use WordPress HTTP api
  $response = wp_remote_get( $api_endpoint, array( 'timeout' => 2 ) );
	
  if( !is_wp_error( $response ) ) {
	  
    // CONSUME THE DATA
    
  }
}