有没有办法防止地图从某个缩放级别向外缩放?我尝试取消鼠标滚轮滚动事件(以防缩小),并隐藏放大/缩小控件。
map.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent arg0) {
int newZoom = map.getZoom();
if (lastZoom < newZoom) {
zoomIn = true;
} else {
arg0.consume();
zoomIn = false;
}
只是为了确保:我想允许缩放,但直到特定的缩放级别。
谢谢
您可以扩展JMapViewer
以覆盖setZoom()
方法。例如:
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
public class TestMapZoom {
static class CustomMap extends JMapViewer {
private int maxZoomLevel;
public CustomMap() {
this.maxZoomLevel = 7;
}
public int getMaxZoomLevel() {
return maxZoomLevel;
}
public void setMaxZoomLevel(int maxZoom) {
this.maxZoomLevel = maxZoom;
}
@Override
public void setZoom(int zoom, Point mapPoint) {
if (zoom < getMaxZoomLevel())
super.setZoom(zoom, mapPoint);
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Demo");
CustomMap viewer = new CustomMap();
frame.add(viewer);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
编辑:没有JMapViewer
扩展名的版本
另一种不需要扩展JMapViewer
稍微简洁的方法可能是替换地图使用的控制器。默认JMapViewer
构造函数安装DefaultMapController
,此示例使用控制器的另一个构造函数和扩展版本:
import java.awt.event.MouseWheelEvent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.openstreetmap.gui.jmapviewer.DefaultMapController;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.MemoryTileCache;
public class TestMapZoom2 {
static class CustomMapController extends DefaultMapController {
private int maxZoomLevel;
public CustomMapController(JMapViewer map) {
super(map);
this.maxZoomLevel = 7;
}
public int getMaxZoomLevel() {
return maxZoomLevel;
}
public void setMaxZoomLevel(int maxZoom) {
this.maxZoomLevel = maxZoom;
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getWheelRotation() < 0 && map.getZoom() >= getMaxZoomLevel())
return;
super.mouseWheelMoved(e);
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Demo");
JMapViewer viewer = new JMapViewer(new MemoryTileCache(), 8);
new CustomMapController(viewer);
frame.add(viewer);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}