Gravatar for

Question by Mario Bonilla, Feb 14, 2018 11:13 PM

Zip code or city/state distance search.

I have a search box that I want a user to enter a zip code or a city/state and then it calculates the latitude/longitude of that location, and then it finds the closest location of the offices i have stored in the sitecore content tree. How can I do this?

I have sorting working based on my current location. And that seems to be working well. But I haven't figured out this other part.

1 Reply
Gravatar for

Answer by Sébastien Belzile, Feb 15, 2018 11:31 AM

I believe this is the documentation you are looking for.

You need to set the coordinates of your user by code. We call this adding a Geolocation Provider.

The code you need to add will find the `CoveoForSitecoreDistanceResources` component and call its method `setDistance`.

Note: you might be using the `CoveoDistanceResources` component, which is the for Sitecore component equivalent in the Coveo Search UI (the for Sitecore component was so awesome that it was ported to the search UI). If this is the case the method you want to call is named setPosition.

Gravatar for

Comment by François Lachance-Guillemette, Feb 15, 2018 1:28 PM

I would add that this `CoveoDistanceResource` component is a helper component that provides a `@distance` field that can be reused in your Search Interface, but it does not handle zip codes in the Search Box.

However, you can register a custom event handler to the onResolvingPosition event to add your own position provider.


Let's take GoogleApiPositionProvider as an example for a position provider. It is in TypeScript, but you can do the same in JavaScript, you only need to register an object that has the `getPosition()` method which returns a Promise with `latitude` and `longitude`.

For instance:

var customPositionProvider = {
    getPosition: function() {
         return Promise.resolve({latitude: "1234", longitude: "1234"});
Coveo.$$(document.getElementById("YOUR_SEARCH_INTERFACE_ID")).on(Coveo.DistanceEvents.onResolvingPosition, function(args) {

Now the only thing you need is wire the Zip Code/City to a latitude and longitude, and put this code inside the `getPosition` function.

Ask a question