Skip to content

Using Ajax to Fetch Nearby Entries

objectivehtml edited this page Sep 7, 2014 · 1 revision

Overview

Using the currentLocation tag it's easy to plot the user's current location. However, sometimes you need to be able to fetch data nearby a specific user once you have their geolocation data. If a user has a GPS, those coordinates are used. If not the IP will be used to attempt to get the address. First plot a map with the user's current location. Once you have this, you have access to the CurrentLocation and need to add a callback function. In this example, the callback function simply passes the user coordinates in the ajax requests and add the response to the DOM.

Example

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

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

{{ craft.googleMaps.currentLocation('map') }}

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>

<script type="text/javascript">
	$(document).ready(function() {

		map.currentLocation.onPositionChanged = function() {
			// Call the prototype to execute inherited functionality
			GoogleMaps.CurrentLocation.prototype.onPositionChanged.call(this);

			var position = this.getPosition();

			// This should be the url of the ajax search template. 
			// Pass the lat/lng to the search to get nearby entries.
			$.get('/maps/ajax-search', {
				lat: position.lat(), 
				lng: position.lng()
			}, function (data) {
				$('body').append(data);
			});

		};

	});
</script>

Ajax Search Template

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

{% set params = {
	lat: craft.request.getParam('lat'),
	lng: craft.request.getParam('lng'),
	distance: 200
} %}

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

{% for entry in entries %}
	
	{{ craft.googleMaps.data('map', entry.map) }}

{% endfor %}
Clone this wiki locally