Archive

Posts Tagged ‘viewport’

Cancel running JQuery AJAX Request

February 28th, 2012 No comments

I’ve implemented a google map which loads the markers according the current viewport. This can result in a lot of requests if a user is panning / zooming wildly.

Here’s a pattern which cancels requests and only processes the last one:

// Globals
var currentRequestID = 0;
var currentRequest;
var requestTimer;

// Add the Event for reloading the Markers
google.maps.event.addListener(map, 'idle', function () {
	SingleProcessMarkerLoading(map);
});

function SingleProcessMarkerLoading(map) {
	// Clear the "Queue"
	clearTimeout(requestTimer);
	// Abort if a Request is running
	if (currentRequest) { currentRequest.abort(); }
	// Start a new Request
	requestTimer = setTimeout(function () {
		// Get the RequestID, increase for the next Request
		localRequestID = ++currentRequestID;
		// Load the markers
		LoadMarkersForCurrentViewport(map, localRequestID);
	}, 500);
}

function LoadMarkersForCurrentViewport(map, localRequestID) {
	// Get the current Bounds
	var bounds = map.getBounds();

	// Get the Points
	var swPoint = bounds.getSouthWest();
	var nePoint = bounds.getNorthEast();

	// Get the Coordinates
	var swLat = swPoint.lat();
	var swLng = swPoint.lng();
	var neLat = nePoint.lat();
	var neLng = nePoint.lng();

	// Calculate an Adjustment for increasing the Viewport a little
	var increasePercentage = 0.1;
	var latAdjustment = ((neLat - swLat) * increasePercentage);
	var lngAdjustment = ((neLng - swLng) * increasePercentage);

	// Adjust
	swLat -= latAdjustment;
	swLng -= lngAdjustment;
	neLat += latAdjustment;
	neLng += lngAdjustment;

	// Build the Url to get the Markers for the Viewport
	var url = 'someurl?' + swLat + '|' + swLng + '|' + neLat + '|' + neLng;

	// Get the JSON-Response and process it
	currentRequest = $.get(url, function (data) {
		// Check if the Request is obsolete
		if (localRequestID != currentRequestID) return;
		// Process the Data here
		});
	return;
}
Ad
Categories: Programming Tags: , , ,