Is it possible to change background position by dragging?
I have a html map that uses world map image as its background.
I can make a js function that changes div's background position, but I like to change background position when user click on the map then drag like g开发者_运维百科oogle map.
so I have a sample page here: http://lab.qacode.com/map which uses http://lab.qacode.com/map/map.jpg
I would appreciate any advice or tip.
An easy way to make this work is to use jQuery UI's draggable
HTML
<div id="map">
<div class="map-canvas"></div>
</div>
JavaScript
// Pre-select elements
var map = $("#map"),
canvas = map.find(".map-canvas");
// Calculate canvas constraints
var maxLeft = map.width()-canvas.width(),
maxTop = map.height()-canvas.height();
// Make canvas draggable
canvas.draggable({
drag: function(e, ui) {
// Check if canvas is within constraints
if (ui.position.left > 0) {
ui.position.left = 0;
} else if (ui.position.left < maxLeft) {
ui.position.left = maxLeft;
}
if (ui.position.top > 0) {
ui.position.top = 0;
} else if (ui.position.top < maxTop) {
ui.position.top = maxTop;
}
}
});
Placing markers
It's possible to place a marker (or whatever) on the map. It's very easy, and the coords are based on pixels within the canvas. For the marker in the test case it's 150px from left and top of canvas.
// Create simple dot marker
$("<div></div>")
.addClass("map-marker")
.appendTo(canvas)
.offset(function(){
return { left: 150, top: 150 };
})
// Append a label
.append("<span><- Dot</span>");
Now to something a little more advanced, namely the (in)famous Google Maps pin.
// Create draggable Google Maps pin marker
var pin =
$("<div></div>")
.addClass("google-pin")
.appendTo(canvas)
.offset(function(){
return { left: 50, top: 50 };
})
// Bind mouseup/down for visual confirmation of grab
.bind({
mousedown: function(){
var os = pin.offset();
pin.offset(function(){
return { top: os.top-3 };
});
},
mouseup: function(){
var os = pin.offset();
pin.offset(function(){
return { top: os.top+3 };
});
}
})
// Make it draggable
.draggable({
start: function(e,ui){
ui.helper.offset(function(){
return { top: ui.offset.top-2 };
});
},
container: canvas
});
See test case on jsFiddle
精彩评论