$49

Smart Map

Documentation  •  Changelog

Documentation

Sorting entries by closest locations

Twig template

Include this in your "craft.entries" call:

.myFieldHandle(params).order('distance')

This will tell Craft to:

  • Filter your Address field with the parameters you specify.
  • Order the results by closest distance from your specified target.
{# example.com/search?near=90210 #}

{% set target = craft.request.getParam('near') %}
{% set params = {
    target: target,
    range: 100
} %}

{% set entries = craft.entries.myFieldHandle(params).order('distance').find() %}

<h1>Showing results for "{{ target }}"...</h1>
{% for entry in entries %}
    <h2>{{ entry.title }}</h2>
    <div>
        {{ entry.myFieldHandle.street1 }}<br />
        {{ entry.myFieldHandle.street2 }}<br />
        {{ entry.myFieldHandle.city }}, {{ entry.myFieldHandle.state }} {{ entry.myFieldHandle.zip }}<br>
        <strong>{{ entry.myFieldHandle.distance | number_format(1) }} miles away</strong>
    </div>
{% else %}
    <h2>No results found</h2>
{% endfor %}

Your target can be anything that translates into a full or partial address...

  • 90210
  • Aurora, IL
  • 742 Evergreen Terrace

Or you can even use specific coordinates (lat,lng) as your target...

  • 38.897659,-77.036587

All parameters are optional.

ParameterDefaultDescription
target(autodetects)Starting point for proximity search
range25Search radius, measured in "units"
units"miles"Units of measurement ("miles" or "kilometers")

PHP in a separate plugin

This operates very similarly to how it's done in Twig:

Craft 3

$entries = Entry::find()
    ->myFieldHandle([
        'target' => 90210,
        'range' => 100
    ])
    ->orderBy('distance')
    ->all();

Craft 2

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->myFieldHandle = array(
    'target' => 90210,
    'range' => 100
);
$criteria->order = 'distance';

$entries = $criteria->find();