Map search: change field placeholder text and auto-append country name to search

We've found the map search feature to be very useful, but we're based in Australia and have found that simple postal code and suburb/city searches do not work unless the country name is appended.

Also, the default placeholder text of the search field refers to 'zip codes', which is a term not used here — the equivalent are called 'postcodes' in Australia.

The following code addresses these two issues using the custom Javascript API:

  1. It replaces the placeholder text with the value assigned to the `searchPlaceholder` variable. In the snippet, we've set this to 'Suburb or Postcode', but any text can be used.
  2. On form submission, it automatically appends the value of `defaultCountry` to the search term, only if if the term does not already contain it. For example, in the snippet, we've used 'Australia', so a postal code search of '3141' will be changed to '3141 Australia' when the form is submitted.

Hopefully others find this useful. To use in your app, change `view_2` to match the view containing your map search, and update the values of `searchPlaceholder` and `defaultCountry` as required.


// Fires on render of view_2
$(document).on('knack-view-render.view_2', function(event, view, data) {
  // Custom settings for the map search
  var searchPlaceholder = 'Suburb or Postcode';
  var defaultCountry = 'Australia';
  // Set up a ref to the input field
  var mapInput = $('#view_2 .kn-map-input').eq(0);
  // Override the placeholder text for the map input
  mapInput.attr('placeholder', searchPlaceholder);
  // On click of Search, append defaultCountry
  // if the search term doesn't already contain it
  $('#view_2 .kn-map-submit').on('click', function() {
    if (mapInput.val().match(new RegExp('^((?!' + defaultCountry + ').)+$'))) {
      mapInput.val($.trim($.trim(mapInput.val()) + ' ' + defaultCountry));
    }
  })
});

 

Thanks for that, very useful.

Thanks for sharing John - and fellow Aussie.