MapPanel

本文介绍了一个地图操作面板的实现细节,包括地图的基本操作如放大、缩小、全屏、漫游等功能,以及高级功能如点击查询、拉框查询、输入坐标定位等。文中详细描述了这些功能的具体实现方式。
部署运行你感兴趣的模型镜像
/**地图显示面板,主要用于显示地图,以及相应与地图相关的一些操作,如放大、缩小、全屏、漫游、刷新、点击查询地图、拉框查询地图、输入坐标定位等操作
* @version .1
* @author lozpeng
* @copyRight CAF.GIS.Dep
* @date 2008/05/27
*/
var MapPanel=function()
{
this.jg=null; //网页画图的类
var mapPanelID="regionMap";
this.drawShapeAction=null;
this.drawShape={x:0,y:0,width:0,height:0};
this.orginPt=null; //鼠标落下时的位置
this.gisActions={
zoomIn:"drawZoomInRectangle", //放大操作
zoomOut:"drawZoomOutRectangle", //缩小操作
identify:"identify", //点击查询图形信息
rectSearch:"drawSearchRectangle",//拉框查询图形信息
mapPan :"mapPan" //地图移动
}

//----工具栏定义开始
var zoomIn = new Ext.Toolbar.Button({
text :'放大',
enableToggle:true
,iconCls :"gis-zoomin"
,toggleHandler:toggleEventHandler.createDelegate(this)
,handler:function(){this.drawShapeAction=this.gisActions.zoomIn;}.createDelegate(this)
,toggleGroup:'gisTools'
});
var zoomOut = new Ext.Toolbar.Button({
text :'缩小'
,enableToggle:true
,toggleHandler:toggleEventHandler.createDelegate(this)
,handler:function(){this.drawShapeAction=this.gisActions.zoomOut;}.createDelegate(this)
,iconCls :"gis-zoomout"
,toggleGroup:'gisTools'
});
var fullExt = new Ext.Toolbar.Button({
text: '全屏'
,enableToggle:false
,iconCls :"gis-fullext"
,handler:fullExtentMapHandler.createDelegate(this)
});
var mapPan = new Ext.Toolbar.Button({
text: '漫游'
,enableToggle:true
,toggleHandler:toggleEventHandler.createDelegate(this)
,iconCls :"gis-pan"
,handler:function(){this.drawShapeAction=this.gisActions.mapPan;}.createDelegate(this)
,toggleGroup:'gisTools'
});
var refresh = new Ext.Toolbar.Button({
text: '刷新'
,enableToggle:false
,iconCls :"gis-refresh"
,handler:function(){alert(this);}.createDelegate(this)
});

var identy =new Ext.Toolbar.Button({
text: '点击查询'
,enableToggle:true
,iconCls :"gis-indentify"
,toggleHandler:toggleEventHandler.createDelegate(this)
,handler:function(){this.drawShapeAction =this.gisActions.identify}.createDelegate(this)
,toggleGroup:'gisTools'
});
var extSearch = new Ext.Toolbar.Button({
text: '拉框查询'
,enableToggle:true
,iconCls :"gis-extsearch"
,toggleHandler:toggleEventHandler.createDelegate(this)
,handler:function(){this.drawShapeAction =this.gisActions.rectSearch}.createDelegate(this)
,toggleGroup:'gisTools'
});
var condiSearch = new Ext.Toolbar.Button({
text: '条件查询'
,enableToggle:false
,handler:function()
{
var wind = Ext.WindowMgr.get(ConditionSearchWindow.prototype.windID);
if(wind)
Ext.WindowMgr.bringToFront(wind);
else
new ConditionSearchWindow().show();
wind = null;
}
});
var coordLocate = new Ext.Toolbar.Button({
text: '输入坐标定位'
,enableToggle:false
,handler:function()
{
regionApp.loadPModal("test","统计图","data/test.jsp",{param1: "foo", param2: "bar"});
}
});
var upLoadData = new Ext.Toolbar.Button({
text: '数据上传'
,enableToggle:false
,handler:function()
{
new ExtSwfFileupload().show();
}
});
var logOff=new Ext.Toolbar.Button({
text:"用户注销"
,handler:function()
{
Ext.Ajax.request({
url:'userManager/logOff.jsp',
method: 'POST',
callback: function(request, success, response) {
var obj = Ext.decode(response.responseText);
if (obj.msg) {
Ext.Msg.show({title:"退出登录失败",msg:obj.msg,buttons: Ext.Msg.OK,icon: Ext.MessageBox.INFO});
return;
}
if (!success) {
Ext.Msg.show({title:"退出登录失败",msg:"对不起,与服务器交互时失败<br>请重试.",buttons: Ext.Msg.OK,icon: Ext.MessageBox.INFO});
return;
}
if(success)
{
Ext.Msg.show({title:"注销成功",msg:"请关闭本页面",buttons: Ext.Msg.OK,icon: Ext.MessageBox.INFO,fn: function(btn,text){
if (btn == 'ok'){
//window.open('index.jsp', 'newwindow', 'height=768, width=1024, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
window.close();
}
}});
}
}
});
}
});

//响应按钮的toggle事件
function toggleEventHandler(button,state)
{
if(!state)
{
alert(button.text);
this.drawShapeAction=null;
}
}
function fullExtentMapHandler()
{
alert("全屏地图!");
}
//-----工具栏定义完

//地图显示界面的状态信息
var clock = new Ext.Toolbar.TextItem('');//状态条上的时间信息
this.mapInfo= new Ext.Toolbar.TextItem({id:'mapInfo',text:"坐标信息:"});

var statusBar = new Ext.StatusBar({
id: 'region.statusbar'
,statusAlign:'right'
,busyText :'加载中...'
,items: [this.mapInfo,'->','-'
,{
text : '刷新坐标信息'
,handler:refreshCoordHandler.createDelegate(this)
}, '-', '当前时间: ', clock]
});

//刷新坐标信息
function refreshCoordHandler()
{
//alert("请响应刷新坐标事件!");
statusBar.showBusy();
Ext.fly(this.mapInfo.getEl()).update("获取坐标信息:",true);
statusBar.clearStatus();
};

/**响应鼠标点击事件
*
*/
this.mouseDown=function mouseDownhandler(e)
{
e.preventDefault();
if(!this.jg)
this.jg = new jsGraphics(this.body);
if(this.drawShapeAction==null)return;//如果鼠标点击时未定义画图操作时跳出点击事件
var position = this.getPosition(false);
var headerHeight = this.getTopToolbar().getSize().height;

var x = e.xy[0]-position[0];
var y = e.xy[1]-position[1]-headerHeight;
this.orginPt={x:x,y:y};
//清除客户端通过js画的图
this.jg.setStroke(1);
this.jg.clear();
};
/**响应鼠标点击事件
*
*/
this.mouseMove=function mouseMoveHandler(e)
{
e.preventDefault();
var position = this.getPosition(false);
var headerHeight = this.getTopToolbar().getSize().height;
var info = "BUTTON"+e.button+"X:"+(e.xy[0]-position[0])+"Y:"+(e.xy[1]-position[1]-headerHeight);
if(this.orginPt==null)return;
var width = (e.xy[0]-position[0])-this.orginPt.x;
var height=(e.xy[1]-position[1]-headerHeight)-this.orginPt.y;
this.updateStatus1(info);
this.drawShape.x=this.orginPt.x;
this.drawShape.y=this.orginPt.y;
this.drawShape.width = width;
this.drawShape.height = height;
mapActionHandler(this);
};
/**鼠标弹起事件监听
*
*/
this.mouseUp=function mouseUpHandler(e)
{
e.preventDefault();
if(this.drawShapeAction==null)return;
var position = this.getPosition(false);
var headerHeight = this.getTopToolbar().getSize().height;
var endPtX = e.xy[0]-position[0];
var endPtY = e.xy[1]-position[1]-headerHeight;

var width = endPtX-this.orginPt.x;
var height = endPtY -this.orginPt.y;
var button =e.button;

if(this.jg)
{
this.jg=null;
}
if(!this.jg)
this.jg = new jsGraphics(this.body);

if(Ext.isIE&&button==0)//如果是IE浏览器且鼠标左键按下
{
if(this.drawShapeAction===this.gisActions.zoomIn)//如果为地图放大操作
{

}
else
{
alert(this.drawShapeAction);
}
}
else if(Ext.isGecko&&button==0)//Gecko是指Mozilla FireFox系列
{

if(this.drawShapeAction===this.gisActions.zoomIn)//如果为地图放大操作
{
this.jg.clear();
this.jg.setColor("#0000ff"); // blue
this.jg.fillRect(this.orginPt.x, this.orginPt.y, width, height);
this.jg.paint();
}
else
{
alert(this.drawShapeAction);
}
}
this.jg.clear();
this.jg=null;
this.orginPt=null;//画图完成之后清除保留的原始坐标点
};
/**更新任务栏的坐标信息
*
*/
this.updateStatus1 = function(info)
{
Ext.fly(this.mapInfo.getEl()).update("坐标信息:"+info,true);
};
this.initJSGraphic=function()
{
if(!this.jg&&this.body)
this.jg = new jsGraphics(this.body);
// this.jg.setColor("#ff0000"); // red
// this.jg.drawLine(2, 2, 220, 55); // co-ordinates related to "myCanvas"
// this.jg.setColor("#0000ff"); // blue
// this.jg.fillRect(110, 120, 30, 60);
// this.jg.paint();
}
/**画一个没有填充颜色的多边形,并响应一个地图操作,如放大,缩小,点击等地图操作事件
*
*/
function mapActionHandler(eventSource)
{
if(eventSource.jg)
{
switch(eventSource.drawShapeAction)
{
case eventSource.gisActions.zoomIn:

case eventSource.gisActions.zoomOut:
case eventSource.gisActions.identify:

}
eventSource.jg.clear();
eventSource.jg.setColor("#0000ff"); // blue
eventSource.jg.drawRect(eventSource.drawShape.x, eventSource.drawShape.y, eventSource.drawShape.width, eventSource.drawShape.height);
eventSource.jg.paint();
}
}

var params = 'optId=init&timeStamp=' + new Date().getTime() + '&width=' + 300 + '&height=' + 400
//地图显示界面的构造函数。
MapPanel.superclass.constructor.call(this,{
title :'全国林发展区划图'
,id :mapPanelID
,bodyStyle :'padding:0px'
,autoScroll : false
//,width :'auto'
//,height :'auto'
,tbar :[zoomIn,zoomOut,mapPan,identy,extSearch,fullExt,refresh,condiSearch,coordLocate,upLoadData,{xtype: 'tbfill'},logOff]
,bbar : statusBar
,listeners : {
'render': {
fn : function(){
this.body.on({'mousemove':this.mouseMove.createDelegate(this)});
this.body.on({'mousedown':this.mouseDown.createDelegate(this)});
this.body.on({'mouseup':this.mouseUp.createDelegate(this)});
//this.initJSGraphic();
Ext.fly(clock.getEl().parentNode).addClass('x-status-text-panel');
Ext.TaskMgr.start({
run: function(){
Ext.fly(clock.getEl()).update(new Date().format('g:i:s A'));
},
interval: 1000
});
},
scope:this
}
}
,autoLoad:{
url: "dispMap.jsp",
params: params,
callback: function(){
alert("file");
},
scope: this,
discardUrl: true,
nocache: true,
text: "地图加载中....",
timeout: 60,
scripts: true
}
});
}
Ext.extend(MapPanel,Ext.Panel,{
updateStatus:function(info)
{
Ext.fly(this.mapInfo.getEl()).update("坐标信息:"+info,true);
},
getID:function()
{
return mapPanelID;
}
/*
,initMap:function()
{
var lon = 5;
var lat = 40;
var zoom = 5;
var map, layer;
map = new OpenLayers.Map( 'regionMap', { controls: [] } );
//map = new OpenLayers.Map(mapPanel,{controls:[]});
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(layer);

var vlayer = new OpenLayers.Layer.Vector( "Editable" );
map.addLayer(vlayer);


var zb = new OpenLayers.Control.ZoomBox(
{title:"Zoom box: Selecting it you can zoom on an area by clicking and dragging."});
var panel = new OpenLayers.Control.Panel({defaultControl: zb});
panel.addControls([
new OpenLayers.Control.MouseDefaults(
{title:'You can use the default mouse configuration'}),
zb,
new OpenLayers.Control.DrawFeature(vlayer, OpenLayers.Handler.Path,
{title:'Draw a feature'}),
new OpenLayers.Control.ZoomToMaxExtent({title:"Zoom to the max extent"})
]);
map.addControl(panel);
map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);

map.events.register("mousemove", map, function(e) {
var position = this.events.getMousePosition(e);
//Ext.fly(mapInfo.getEl()).update("坐标信息:"+position,true);
//this.updateStatus1(position);
var mapPanel = Ext.getCmp("regionMap");
if(mapPanel)
mapPanel.updateStatus(position);
else
this.updateStatus(position);
});
this.doLayout();
}*/
});
有点乱,没时间整理。先放着吧。

您可能感兴趣的与本文相关的镜像

PyTorch 2.6

PyTorch 2.6

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

package com.app; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.*; import java.net.Socket; import java.nio.ByteBuffer; import java.util.List; import java.util.*; public class AGVClient extends JFrame { private final JLabel videoLabel = new JLabel("视频流加载中...", SwingConstants.CENTER); private final JPanel mapPanel = new MapPanel(); // 自定义面板用于地图和路径绘制 private BufferedImage currentImage = null; private BufferedImage mapImage = null; private Socket videoSocket, mapSocket; private DataInputStream videoIn; private PrintWriter mapOut; private BufferedReader mapIn; private int gridSize = 20; // 模拟地图缩放比例(可调) private Point startPoint = null, endPoint = null; private List<Point> pathPoints = new ArrayList<>(); public AGVClient() { setTitle("AGV远程监控客户端"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(1200, 600); setLayout(new BorderLayout()); // 左侧:视频流 videoLabel.setPreferredSize(new Dimension(640, 480)); videoLabel.setOpaque(true); videoLabel.setBackground(Color.BLACK); add(new JScrollPane(videoLabel), BorderLayout.WEST); // 右侧:地图面板 mapPanel.setPreferredSize(new Dimension(500, 500)); mapPanel.setBackground(Color.LIGHT_GRAY); mapPanel.setBorder(BorderFactory.createTitledBorder(" 导航地图")); mapPanel.addMouseListener(new MapClickListener()); add(new JScrollPane(mapPanel), BorderLayout.EAST); connectToServer(); startVideoThread(); startMapListener(); } private void connectToServer() { try { // 连接视频流 videoSocket = new Socket("localhost", 6000); // 替换为实际IP videoIn = new DataInputStream(videoSocket.getInputStream()); System.out.println("🎥 已连接至视频流服务器"); // 连接地图服务 mapSocket = new Socket("localhost", 6001); mapOut = new PrintWriter(mapSocket.getOutputStream(), true); mapIn = new BufferedReader(new InputStreamReader(mapSocket.getInputStream())); System.out.println("🗺️ 已连接至地图服务"); } catch (IOException e) { JOptionPane.showMessageDialog(this, "无法连接到服务器: " + e.getMessage(), "连接错误", JOptionPane.ERROR_MESSAGE); System.exit(1); } } private void startVideoThread() { new Thread(() -> { try { while (!videoSocket.isClosed()) { // 读取图像大小(4字节大端) byte[] sizeBytes = new byte[4]; int bytesRead = 0; while (bytesRead < 4) { bytesRead += videoIn.read(sizeBytes, bytesRead, 4 - bytesRead); } int imageSize = ByteBuffer.wrap(sizeBytes).getInt(); // 读取图像数据 byte[] imageBytes = new byte[imageSize]; bytesRead = 0; while (bytesRead < imageSize) { bytesRead += videoIn.read(imageBytes, bytesRead, imageSize - bytesRead); } // 解码图像 ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes); BufferedImage img = ImageIO.read(bais); if (img != null) { currentImage = img; videoLabel.setIcon(new ImageIcon(img)); videoLabel.repaint(); } // 从当前帧生成灰度图作为地图底图(模拟) generateMapFromFrame(img); } } catch (Exception e) { if (!videoSocket.isClosed()) e.printStackTrace(); JOptionPane.showMessageDialog(this, "视频流中断", "错误", JOptionPane.WARNING_MESSAGE); } }).start(); } private void generateMapFromFrame(BufferedImage frame) { int w = frame.getWidth() / 4; int h = frame.getHeight() / 4; BufferedImage small = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g = small.createGraphics(); g.drawImage(frame.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0, 0, null); g.dispose(); mapImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { int gray = new Color(small.getRGB(x, y)).getRed(); int color = gray < 120 ? 0x000000 : 0xFFFFFF; // 黑色障碍,白色自由区 mapImage.setRGB(x, y, color); } } mapPanel.repaint(); } private void startMapListener() { new Thread(() -> { try { String line; while ((line = mapIn.readLine()) != null) { System.out.println("📡 收到路径: " + line); JSONObject json = parseJSON(line.trim()); if (json.containsKey("path")) { List<Point> newPath = new ArrayList<>(); List<List<Integer>> rawPath = (List<List<Integer>>) json.get("path"); for (List<Integer> p : rawPath) { newPath.add(new Point(p.get(0), p.get(1))); } pathPoints = newPath; mapPanel.repaint(); } } } catch (Exception e) { e.printStackTrace(); } }).start(); } class MapPanel extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (mapImage != null) { g.drawImage(mapImage, 0, 0, getWidth(), getHeight(), null); // 绘制网格线(可选) int w = mapImage.getWidth(), h = mapImage.getHeight(); int pw = getWidth() / w, ph = getHeight() / h; g2d.setColor(Color.LIGHT_GRAY); for (int i = 0; i <= w; i++) g2d.drawLine(i * pw, 0, i * pw, getHeight()); for (int j = 0; j <= h; j++) g2d.drawLine(0, j * ph, getWidth(), j * ph); } // 绘制路径 g2d.setColor(Color.GREEN); g2d.setStroke(new BasicStroke(3)); for (int i = 0; i < pathPoints.size() - 1; i++) { Point a = pathPoints.get(i); Point b = pathPoints.get(i + 1); g2d.drawLine(a.x * pw(), a.y * ph(), b.x * pw(), b.y * ph()); } // 绘制起点(蓝色) if (startPoint != null) { g2d.setColor(Color.BLUE); g2d.fillOval(startPoint.x * pw() - 5, startPoint.y * ph() - 5, 10, 10); } // 绘制终点(红色) if (endPoint != null) { g2d.setColor(Color.RED); g2d.fillOval(endPoint.x * pw() - 5, endPoint.y * ph() - 5, 10, 10); } } private int pw() { return getWidth() / (mapImage != null ? mapImage.getWidth() : 1); } private int ph() { return getHeight() / (mapImage != null ? mapImage.getHeight() : 1); } } class MapClickListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if (mapImage == null) return; int x = e.getX() / mapPanel.pw(); int y = e.getY() / mapPanel.ph(); if (x < 0 || x >= mapImage.getWidth() || y < 0 || y >= mapImage.getHeight()) return; if (SwingUtilities.isLeftMouseButton(e)) { startPoint = new Point(x, y); sendWaypoints(); } else if (SwingUtilities.isRightMouseButton(e)) { endPoint = new Point(x, y); sendWaypoints(); } } } private void sendWaypoints() { if (mapOut == null || mapOut.checkError()) return; Map<String, Object> msg = new HashMap<>(); if (startPoint != null) { msg.put("start", Arrays.asList(startPoint.x, startPoint.y)); } if (endPoint != null) { msg.put("end", Arrays.asList(endPoint.x, endPoint.y)); } mapOut.println(new JSONObject(msg).toString()); System.out.println("📤 发送路径请求: " + msg); } // 简易 JSON 实现(避免依赖外部库) static class JSONObject extends LinkedHashMap<String, Object> { public JSONObject(Map<String, Object> m) { super(m); } @Override public String toString() { StringBuilder sb = new StringBuilder("{"); Iterator<Map.Entry<String, Object>> it = entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> e = it.next(); sb.append("\"").append(e.getKey()).append("\":"); Object v = e.getValue(); if (v instanceof List) { sb.append(listToString((List<?>) v)); } else if (v instanceof String) { sb.append("\"").append(v).append("\""); } else { sb.append(v); } if (it.hasNext()) sb.append(","); } sb.append("}"); return sb.toString(); } private String listToString(List<?> list) { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < list.size(); i++) { Object o = list.get(i); if (o instanceof List) { sb.append(listToString((List<?>) o)); } else if (o instanceof String) { sb.append("\"").append(o).append("\""); } else { sb.append(o); } if (i < list.size() - 1) sb.append(","); } sb.append("]"); return sb.toString(); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel()); } catch (Exception ignored) {} new AGVClient().setVisible(true); }); } }将上述程序换为相同功能android studio的程序
最新发布
10-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值