Evaluating google maps JSON response with Ajax

DHMG

New Member
Hello community!

After a lot of searching around and googling I got it almost to work, but I hit a wall at the end.
Would be great if someone here would help me to finish this little project of mine.

I want to make a form that takes a user input (Address, in a geolocate Text field), evaluates that address with google maps API and calculates the distance between a static location and the users location. If the distance between these locations is bigger than 5000 meters it should set a field value to X; otherwise it should set the field to Y.

I added a JS event to the geolocate Address field (id 'lieferadresse'), that calls the function "getAddress()" . The URL gets assembled in the field with the id 'ggl_url'. So far this is all working fine.
I added the file "1.js" in / components / com_fabrik / js
and "user_ajax.php" in / components / com_fabrik
Here are the contents of both files:
1.js
JavaScript:
function getAddress() {
    var api ='';
    var pre ='https://maps.googleapis.com/maps/api/distancematrix/json?origins=';
    var origins = 'Bahnhofstraße+13+6112+Wattens';
    var destinations = (Fabrik.getBlock('form_1').formElements.get('fabrikdata_blumen_bestellen_liefern___lieferadresse').getValue()).replace(/ /g, '+');
    Fabrik.getBlock('form_1').formElements.get('fabrikdata_blumen_bestellen_liefern___ggl_url').update(pre+origins+'&destinations='+destinations+'&key='+api);
    testCode();
}
function testCode() {
    var identify = Fabrik.getBlock('form_1').formElements.get('fabrikdata_blumen_bestellen_liefern___ggl_url').getValue(); //field to set JS event on
    /*contains something like this:
    https://maps.googleapis.com/maps/api/distancematrix/json?origins=Himmelreichweg+12+6112+Wattens&destinations=Bahnhofstra%C3%9Fe+13,+6112+Wattens,+%C3%96sterreich&key=apikey
    */
    var update = $('fabrikdata_blumen_bestellen_liefern___ggl_result'); //this is the field that should display the distance value of the evaluated JSON response
    var data = {
        'option'    : 'com_fabrik',
        'format'    : 'raw',
        'task'      : 'plugin.userAjax',
        'method'    : 'evalJsonResponse',
        'identify'    : identify
    };
    console.debug(data); //identify contains the correct url string, but how do I send it / store the response?

    new Request({
        'url': '',
        'data': data,
        onComplete:function(r){
            update.value = r;
        }
    }).send();
}

user_ajax.php
PHP:
class userAjax {
    function evalJsonResponse( $json ){
        /*Go through the JSON data*/
        /*But how do I pass on $json?*/
        $jsonIterator = new RecursiveIteratorIterator(
        new RecursiveArrayIterator(json_decode($json, TRUE)),
        RecursiveIteratorIterator::SELF_FIRST);

        foreach ($jsonIterator as $key => $val) {
            if(is_array($val)) {
                echo "$key:\n";
            } else {
                echo "$key => $val\n";
            }
        }
        exit();
    }
}

The problem is that I don't know how to call the url / store the response from the google API in a variable and pass it to the php function.
It shouldn't be a big problem, but I seem to have entered blockhead mode and can't figure it out.

The response I would get from the google API will look like this:
Code:
{
   "destination_addresses" : [ "Hermine Berghofer-Straße 50/52, 6130 Schwaz, Österreich" ],
   "origin_addresses" : [ "Himmelreichweg 12, 6111 Wattens, Österreich" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "16,3 km",
                  "value" : 16341
               },
               "duration" : {
                  "text" : "16 Minuten",
                  "value" : 964
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
I am interested in getting the values for:
rows -> elements -> distance -> value
rows -> elements -> status
which shouldn't be that hard with some modifications to the recursive foreach function I use in user_ajax.php.

Any help would be greatly appreciated.

Cheers,
Mario
 
I am an idiot and I blame my lack of coffee.

I don't need ajax at all, this can be done in JS alone. Will post the finished code later today for other people to use.

Edit: Was easier than expected.
Just call "prepareAdress()" in a JS Event of your choice on a geolocate text field, add the code below to a file named <form_id>.js to /components/com_fabrik/js and edit it to fit your needs.
Make sure you add your google maps API key in fabrik and to set up proper validation for your result field. If the user enters an empty or an invalid address the validation field will be emptied, otherwise it will display the distance between 2 locations.

JavaScript:
function prepareAddress() {
    var origin = 'Some Streetname 9, some city here, country'; //first address
    var destination = Fabrik.getBlock('form_1').formElements.get('listid___elementid_user_input').getValue(); //second address provided by user input
    calcDistance(origin, destination);
}

function calcDistance(origin1, destinationA) {
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
        origins: [origin1],
        destinations: [destinationA],
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.METRIC, //change to IMPERIAL if needed
        avoidHighways: false,
        avoidTolls: false,
    }, callback);
}

function callback(response, status) {
    if (status !== 'OK' || response.destinationAddresses == '' || response == null) {
        Fabrik.getBlock('form_1').formElements.get('listid___elementid_result').update(''); //On Error empty the validation field
    } else {
        var origins = response.originAddresses;
        var destinations = response.destinationAddresses;

        for (var i = 0; i < origins.length; i++) {
            var results = response.rows[i].elements;
            for (var j = 0; j < results.length; j++) {
                var element = results[j];
                var distance = element.distance.text;
                var duration = element.duration.text;
                var from = origins[i];
                var to = destinations[j];
            }
        }
        Fabrik.getBlock('form_1').formElements.get('listid___elementid_result').update(results[0].distance.value); //else update the validation field with the distance value
    }
}
 
Last edited:
We are in need of some funding.
More details.

Thank you.

Members online

Back
Top