Skip to content

Search by Proximity

Justin Kimbrell edited this page Apr 7, 2015 · 4 revisions

Overview

At times you may want to fetch entries by proximity to a location. This scenario is useful for store finders or anytime you want to search for map data to calculate a distance. Google Maps for Craft allows you to fetch entries by an address string or a specific coordinate. In this example, you can see how to fetch entries in relation to a specified address. The results are then plotted on a map and displayed in the template. There are additional variables that can be output, but this represents the basic use case.

Note, when you want to sort by the proximity you must use the following format yourMapField_distance. When the query is built, the field name is prepended to the distance column.

Example

{% set query = craft.request.getParam('q') %}

{% set params = {
	address: query,
	distance: 200,
	unit: 'miles'
} %}

{% set entries = craft.entries.map(params).order('map_distance asc') %}

<form action="{{ url('/maps/search') }}" class="search-form clearfix">
	<input type="text" name="q" value="{{ query }}" id="q">
	<button type="submit">Search</button>	
</form>

<h3>Search Results</h3>

{% set options = {
	id: 'map', 
	width: '400px', 
	height: '300px'
} %}

{{ craft.googleMaps.map(options) }}

<ul class="search-results">
{% for entry in entries %}
	<li>
		<h4><a href="{{ entry.url }}">{{ entry.title }}</a></h4>

		{{ craft.googleMaps.data('map', entry.map) }}

		{% for marker in entry.map.markers() %}

			<p>
				<b>{{ marker.title }} - {{ marker.distance }}</b> <br>
			</p>

		{% endfor %}
	</li>
{% endfor %}
</ul>