Gravatar for

Question by coveositecore, Sep 9, 2016 3:54 PM

Call Google to get lat long before every search

Hi, I'm using Coveo for address search. So each time a user enters a query (address/zip/city etc.), I want to return 10 closest locations.

So for every single search attempt, I want to call Google to convert user query to lat long (I got this working; see below code) before I initialize/pass lat long to Coveo.

How can I intercept the call to "newQuery" or in other words how can I make sure that I've lat, long all the time before I call "newQuery"?




convertQueryToLatLng() {          
            var query = "new york";
            var geocoder = new google.maps.Geocoder();

            geocoder.geocode({ 'address': query }, function (results, status) {

                if (status == google.maps.GeocoderStatus.OK) {
                    this._refAddress = {
                        lat: results[0],
                        lng: results[0].geometry.location.lng()

calcDistance(e: JQueryEventObject, args: Coveo.DoneBuildingQueryEventArgs) {
            var geoQuery = "$qf(function:'dist(lat, lng,, this._refAddress.lng)', fieldName: " + distance + ")";
            args.queryBuilder.sortCriteria = "" + distance + " ascending";
1 Reply
Gravatar for

Answer by Martin Laporte, Sep 13, 2016 6:04 AM

It's always somewhat complex to introduce async calls in the process of performing a query.

One thing that might work is to use the cancel flag on the newQuery event ( to stop a query triggered by an end user until the Google API answers back. Then you'd trigger a query again in JS code, and let it pass this time.

Another option would be to call Google on the change event on the query textbox, store the result somewhere, and then use it in buildingQuery. But this means you might have queries with no geo information if they are executed "too fast" (ex: user types and presses enter - a frequent scenario).

All in all I'd look at my first suggestion first :) Maybe someone else can suggest a better answer, too.

Ask a question