Challenge:
You have an address like “1600 Amphitheatre Parkway, Mountain View, CA”.
You need the latitude and longitude of that address.
The general idea for the Solution:
Ask the Google API:
https://maps.googleapis.com/maps/api/geocode/json?address=YOUR_ADRESS&key=YOUR_GOOGLE_KEY
- YOUR_ADRESS: whatever, but url encoded
- YOUR_GOOGLE_KEY: Get one via https://developers.google.com/maps/documentation/javascript/get-api-key
The solution in detail:
Guess you have JSON data and each item has an address. For each address, we’d like to know the latitude and longitude.
For that, we first create a new JCI-Template with these settings:
Template-Text:
{{ _context | json_encode }}
Name of template: googleconvadr2latlon
URL (##param1## we explain later):
https://maps.googleapis.com/maps/api/geocode/json?address=##param1##&key=YOUR_GOOGLE_KEY
Cache time in seconds (this is how long a GoogleAPI-request is locally stored, to avoid many requests on the API): e.g. 31536000 seconds for 1 year
To use this JCI-“googleconvadr2latlon”-Template together with JSON data, you need another JCI-Template.
Template-Text (param1 is used in the other template at “##param1##”):
{% set adr = "1600 Amphitheatre Parkway, Mountain View, CA" %} {% set adr_encoded = adr | url_encode %} {% set sc = '{"error_message":"You must enable Billing on the Google Cloud Project at https:\/\/console.cloud.google.com\/project\/_\/billing\/enable Learn more at https:\/\/developers.google.com\/maps\/gmp-get-started","results":[],"status":"REQUEST_DENIED","param1":"'~adr_encoded~'"}' %} {% set scexe = (sc | doshortcode | json_decode(TRUE)) %} <hr> Google-Answer:<br> {{scexe | json_encode }} <hr> {% if scexe.error_message %} Google tells us: {{scexe.error_message}} {% else %} {% set lat = scexe.results.0.geometry.location.lat %} {% set lng= scexe.results.0.geometry.location.lng %} {{adr}} is at <a href="https://www.google.com/maps/place/{{lat}},{{lng}}" target="_blank" rel="noopener">{{lat}},{{lng}}</a> {% endif %}
Name of template: doadr2latlon
URL: either your JSON-URL or “dummyrequest” for testing
In action:
Google-Answer:
{“error_message”:”You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started”,”results”:[],”status”:”REQUEST_DENIED”,”param1″:”1600%20Amphitheatre%20Parkway%2C%20Mountain%20View%2C%20CA”}
Google tells us: You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started