patternjavascriptMinor
Handler for a control to pan a map in four directions
Viewed 0 times
mapcontrolfourpanfordirectionshandler
Problem
I have a pan control that look like this:
Pretty standard Google Mapsish controls, IMO.
When the user clicks in the top 3rd of the control, it should pan up (deltaY = +1); right third means it should pan east (deltaX = -1); Down is deltaY = -1, and West is deltaX = +1. The control is 50px, square. I have working code, but I believe it can be written much more elegantly than this using a single (if discontinuous) mathematical function.
Pretty standard Google Mapsish controls, IMO.
When the user clicks in the top 3rd of the control, it should pan up (deltaY = +1); right third means it should pan east (deltaX = -1); Down is deltaY = -1, and West is deltaX = +1. The control is 50px, square. I have working code, but I believe it can be written much more elegantly than this using a single (if discontinuous) mathematical function.
$(control).click(function (evt) {
var clickPointX = (evt.layerX || evt.offsetX),
clickPointY = (evt.layerY || evt.offsetY),
deltaX,
deltaY;
// control is 50x50 px.
// Click in the top third, get a positive 'Y' value.
// Click in the left third, get a positive 'X' value.
// Click in the middle, get zero.
if (clickPointX 34) {
deltaX = -1;
} else {
deltaX = 0;
}
if (clickPointY 34) {
deltaY = -1;
} else {
deltaY = 0;
}
map.panDirection(deltaX, deltaY);
});Solution
A few improvements:
Example code:
- replace magic numbers
- extract repetition into a function
- dynamically calculate dimensions
Example code:
function getDelta(clickPoint, controlDimension, threshold){
var delta;
if (clickPoint controlDimension- threshold) {
delta = -1;
} else {
delta = 0;
}
return delta;
}
$(document).ready(function () {
var control = $('#example');
var controlHeight = control.height();
var controlWidth = control.width();
var widthThreshold = controlHeight/3;
var heightThreshold = controlWidth/3;
$(control).click(function (evt) {
var clickPointX = (evt.layerX || evt.offsetX);
var clickPointY = (evt.layerY || evt.offsetY);
var deltaX = getDelta(clickPointX, controlWidth, widthThreshold);
var deltaY = getDelta(clickPointY, controlHeight, heightThreshold);
alert('delta x: ' + deltaX + '\n' + 'delta y: ' + deltaY);
//map.panDirection(deltaX, deltaY);
});
});
Context
StackExchange Code Review Q#6883, answer score: 3
Revisions (0)
No revisions yet.