In this example we'll show you how to add a location search to a Page, and then output the results of that search both in a list and on a map. Items will display in the result set when they are within the radius of a chosen location. One example of how you can use this is as a Store Locator for a franchise of Shops.
Step by Step
1 - Add an HTML Form and JavaScript to take User input to decide starting position and search radius
Two different options are provided in this example:
Current location (using browser default functionality) and desired search radius
Add HTML and JavaScript
HTML
JS
|
<divclass="container text-center"><h1class="mb-3 h2 sg-h2">Search for Stores within your area</h1><divclass="row"><divclass="col-12"><formclass="sg-form"><iclass="fas fa-crosshairs fa-2x mb-2"></i><h3style="margin-bottom: 5rem;">Current Location</h3><divclass="text-start form-group sg-form-group"><labelfor="current_locations_distance">Change search distance (km)</label><inputclass="form-control sg-form-control mb-3"type="number"id="current_locations_distance"value="{{context.params.distance | default: 20}}"/></div><divclass="row"><divclass="col-12 d-flex justify-content-end"><buttonclass="btn btn-primary sg-btn sg-btn-primary btn-lg sg-btn-lg"onclick="getMyLocation()">Find stores near me <iclass="fas fa-arrow-right"></i></button></div></div></form></div></div></div>
2 - Output the results on the Page in a simple list
Use a Layout of your choice.
{%- include 'webapp', id: '1', use_location_search: 'true', layout: 'default' -%}
3 - Output the results on a map
This relies on there being a layout named 'json'. See the contents of 'json' in the 2nd block of code.
Add HTML + Liquid
The Liquid makes sure the map is only outputted after the Page has been refreshed by the JavaScript and the correct parameters are available in the URL for filtering the results.
HTML
|
{%- if context.params.distance and context.params.longlat -%}
<linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.css"integrity="sha512-1xoFisiGdy9nvho8EgXuXvnpR5GAMSjFwp40gSRE3NwdUdIMIKuPa7bqoUhLD0O/5tPNhteAsE5XyyMi5reQVA=="crossorigin="anonymous"/><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.js"integrity="sha512-SeiQaaDh73yrb56sTW/RgVdi/mMqNeM2oBwubFHagc5BkixSpP1fvqF47mKzPGWYSSy4RwbBunrJBQ4Co8fRWA=="crossorigin="anonymous"></script><divid="map"class="map"style="height:400px;width:100%"></div><spanid="map_content"style="display:none">
{%- include 'webapp'
id: '1'
use_location_search: 'true'
type: 'list'
-%}
</span>
{%- endif -%}
Add JavaScript
The following function is triggered by the script from step 1, only after it has finished loading- this occurs because the function's name is referenced in the URL parameter fetching the Script. The code must be placed above the <script> tag from step 1.