zoukankan      html  css  js  c++  java
  • 服务器------3.根据经纬度划分区域

    目标:后台添加区域,前台传某一个经纬度,判定该经纬度是否在该区域内

    1.创建jsp

    <%@ page language="java" import="java.util.*"
        contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@include file="/context/mytags.jsp"%>
    <!DOCTYPE html>  
    <html>  
    <head>  
    <t:base type="jquery,easyui,tools,DatePicker"></t:base>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />  
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
    <title>Hello, World</title>  
    <style type="text/css">  
    html{height:100%}  
    body{height:100%;margin:0px;padding:0px}  
    #container{height:100%}  
        .anchorBL{  
           display:none;  
       }
        .carvesClear {
            background-image:none  !important;
        text-align: center;
        padding-top: 15px;
        background-color: white;
        }
    </style> 
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=akTFtwB1MOHYX0ILEOUTk0Rh">
    //v2.0版本的引用方式:src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"
    //v1.4版本及以前版本的引用方式:src="http://api.map.baidu.com/api?v=1.4&key=您的密钥&callback=initialize"
    </script>
    <script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
    </head>  
     
    <body>  
    <input type="hidden" value="${address }" id = "cityName"/> 
    <input type="hidden" value="${masterid }" id = "masterId"/> 
    <input type="hidden" value="" id ="masterPoints"/>
    <div id="container"></div> 
    <script type="text/javascript"> 
    var map = new BMap.Map('container');        // 创建地图实例  
    
    var cityName = $("#cityName").val();
    //地区形式定位
    map.centerAndZoom(cityName, 14);
    //显示地图区域边界
    function getBoundary() {
        var bdary = new BMap.Boundary();
        bdary.get(cityName, function (rs) {       //获取行政区域
           //map.clearOverlays();        //清除地图覆盖物       
            var count = rs.boundaries.length; //行政区域的点有多少个
            if (count === 0) {
                alert('未能获取当前行政区域的边界');
                return;
            }
            var pointArray = [];
            for (var i = 0; i < count; i++) {
                var ply = new BMap.Polygon(rs.boundaries[i], { strokeWeight: 2, strokeColor: "#ff0000",fillColor:"" }); //建立多边形覆盖物
                map.addOverlay(ply);  //添加覆盖物
                pointArray = pointArray.concat(ply.getPath());
            }
            //map.setViewport(pointArray);    //调整视野                 
        });
    }
    var drawingManager;
    var points = [];
    
    //已保存 、 编辑中的区域
    var saveoverlays = {}, editoverlays = [];
    var overlaycomplete = function (e) {
        editoverlays.push(e.overlay);
    
        //获取绘制的点
        points = e.overlay.ia;
        
        
    };
    getBoundary();
    
    map.enableScrollWheelZoom();
    
    var styleOptions = {
        strokeColor:"red",    //边线颜色。
        fillColor:"red",      //填充颜色。当参数为空时,圆形将没有填充效果。
        strokeWeight: 2,       //边线的宽度,以像素为单位。
        strokeOpacity: 0.8,       //边线透明度,取值范围0 - 1。
        fillOpacity: 0.5,      //填充的透明度,取值范围0 - 1。
        strokeStyle: 'dashed' //边线的样式,solid或dashed。
    }
    
    //实例化鼠标绘制工具
    drawingManager = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
            offset: new BMap.Size(5, 5), //偏离值
            drawingModes: [
                BMAP_DRAWING_POLYGON
            ]
        },
        polygonOptions: styleOptions //多边形的样式
    });
    //drawingManager.enableCalculate();  //面积或距离
     //添加鼠标绘制工具监听事件,用于获取绘制结果
    drawingManager.addEventListener('overlaycomplete', overlaycomplete);
    
    function clearAll() {
        alert(editoverlays);
        for (var i = 0; i < editoverlays.length; i++) {
            map.removeOverlay(editoverlays[i]);
        }
        editoverlays.length = 0;
        points = [];
    }
    
    //绘制
    function allts(pts,vid) {
        //创建多边形
        var strokeColor = "blue", fillColor = "blue";
        if (vid == 0) {
            strokeColor = "#c0c0c0", fillColor = "#c0c0c0";
        }
        var xiancunPolygon = new BMap.Polygon(pts, {
            strokeColor: strokeColor,    //边线颜色。
            fillColor: fillColor,      //填充颜色。当参数为空时,圆形将没有填充效果。
            strokeWeight: 2,       //边线的宽度,以像素为单位。
            strokeOpacity: 0.8,       //边线透明度,取值范围0 - 1。
            fillOpacity: 0.5,      //填充的透明度,取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式,solid或dashed。
        });
        if (vid != 0) {
            xiancunPolygon.addEventListener("click", function (_vid) {
                $.messager.confirm('删除告警提示', '确定要删除此区域?', function(r) {
                    if (r) {
                        $.ajax({
                            type: "post",
                            url: "xnMasterController.do?deleteMasterPoints",
                            data: "id="+vid,
                            dataType: "json",
                            async: false,
                            error : function() {// 请求失败处理函数
                            },
                            success : function(data) {
                                if(data.success){
                                    alert(data.msg);
                                } else {
                                    alert(data.msg);
                                }
                                window.location.reload();
                            }
                        });
                        /* ShuyaJs.postorg({
                            url: "/Oms/OmsJoinSite/ManageAreaDel", data: { Id: vid }, callfun: function (result) {
                                if (result.Code != "0") {
                                    alert(result.Msg);
                                } else {
                                    alert(result.Msg);
                                    window.location.reload();
                                }
                            }
                        }); */
                    }
                });
            });
        }
        saveoverlays[vid] = xiancunPolygon;
        //添加多边形到地图上     
        map.addOverlay(xiancunPolygon);
    }
    
    function SaveCarves() {
        var masterPointslength = $("#masterPoints").val();
        var masterId = $("#masterId").val();
        if (points!=null && points.length>=3 && masterPointslength == 0) {
            $.ajax({
                type: "post",
                url: "xnMasterController.do?saveMasterPoints",
                data: "points="+JSON.stringify(points)+"&id="+masterId,
                dataType: "json",
                async: false,
                error : function() {// 请求失败处理函数
                },
                success : function(data) {
                    if(data.success){
                        alert(data.msg);
                    } else {
                        alert(data.msg);
                    }
                    window.location.reload();
                }
            });
        } else if(masterPointslength != 0){
            alert("站长已经有所画区域,请删除后重新添加!");
        } else{
            alert("请进行绘制区域,并至少有三个点形成一个面");
        }
        
    }
    
    $(".BMapLib_Drawing_panel").append('<a class="BMapLib_box carvesClear" href="javascript:clearAll();" title="清除" >清除</a>');
    $(".BMapLib_Drawing_panel").append('<a class="BMapLib_box carvesClear" href="javascript:SaveCarves();" title="保存" >保存</a>');
    
    $(function () {
        var id = $("#masterId").val();
        $.ajax({
            type: "post",
            url: "xnMasterController.do?masterPoints",
            data: "id="+id,
            dataType: "json",
            async: false,
            error : function() {// 请求失败处理函数
            },
            success : function(data) {
            if(data.obj != null){
                $("#masterPoints").val(data.obj.length);
                allts(data.obj, data.msg);
            }else{
                $("#masterPoints").val(0);
            }
            }
        });
    });
    </script>  
    </body>  
    </html>

    2.创建经纬度实体

    package com.redstoneinfo.infant.entity.baizhuanghui;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    import org.hibernate.annotations.GenericGenerator;
    
    @Entity
    @Table(name="xn_gps_point",schema = "")
    @SuppressWarnings("serial")
    public class XnGpsPoint {
        private String id;//主键id
        private String masterId;//站长id
        private Double lng;//经度
        private Double lat;//纬度
        public XnGpsPoint() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        /**主键id*/
        @Id
        @GeneratedValue(generator = "paymentableGenerator")
        @GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
        @Column(name ="id",nullable=false,length=255)
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        @Column(name ="master_id")
        public String getMasterId() {
            return masterId;
        }
    
        public void setMasterId(String masterId) {
            this.masterId = masterId;
        }
        @Column(name ="lng")
        public Double getLng() {
            return lng;
        }
    
        public void setLng(Double lng) {
            this.lng = lng;
        }
        @Column(name ="lat")
        public Double getLat() {
            return lat;
        }
    
        public void setLat(Double lat) {
            this.lat = lat;
        }
    
        public XnGpsPoint(String id, String masterId, Double lng, Double lat) {
            super();
            this.id = id;
            this.masterId = masterId;
            this.lng = lng;
            this.lat = lat;
        }
    
        
        
        
        
        
    
    }

    3.controller中添加删除修改

        // 为站长划分区域
        @RequestMapping(params = "centerMap")
        public ModelAndView centerMap(XnMaster xnMaster, HttpServletRequest req) {
            if (StringUtil.isNotEmpty(xnMaster.getId())) {
                xnMaster = systemService
                        .getEntity(XnMaster.class, xnMaster.getId());
                // 取出master里面的省市区字段 修改为地图的中心坐标
                req.setAttribute(
                        "address",
                        xnMaster.getShengfen() + xnMaster.getCity()
                                + xnMaster.getArea());
                req.setAttribute("masterid", xnMaster.getId());
            }
    
            return new ModelAndView(
                    "baizhuanghuiPages/xnMaster/xnMasterMap/mapMaster");
        }
    
        // 站长自己的区域
        @RequestMapping(params = "masterPoints")
        @ResponseBody
        public AjaxJson masterPoints(HttpServletRequest request) {
            String id = request.getParameter("id");
            AjaxJson j = new AjaxJson();
            // 根据masterId 取出该站长对应的区域 XnGpsPoint实体
            JSONArray array = new JSONArray();
            List<XnGpsPoint> pointList = this.jeecgJdbcService.findByProperty(
                    XnGpsPoint.class, "masterId", id);
    
            if (pointList.size() > 0) {
                // 站长有自己的区域 需要将区域id设置为站长id
                j.setMsg(id);
                for (int i = 0; i < pointList.size(); i++) {
                    XnGpsPoint point = pointList.get(i);
                    JSONObject ob = new JSONObject();
                    ob.put("lng", point.getLng());
                    ob.put("lat", point.getLat());
                    array.add(ob);
                }
                j.setObj(array);
            }
            return j;
        }
    
        // 删除站长区域信息
        @RequestMapping(params = "deleteMasterPoints")
        @ResponseBody
        public AjaxJson deleteMasterPoints(HttpServletRequest request) {
            // 站长id
            String id = request.getParameter("id");
            AjaxJson j = new AjaxJson();
            // 根据masterId 取出该站长对应的区域 XnGpsPoint实体
            String sql = " delete from xn_gps_point where master_id = '" + id + "'";
    
            this.systemService.executeSql(sql);
            j.setSuccess(true);
            j.setMsg("删除区域成功");
    
            return j;
        }
    
        // 保存站长区域信息
        @RequestMapping(params = "saveMasterPoints")
        @ResponseBody
        public AjaxJson saveMasterPoints(HttpServletRequest request) {
            // 站长id
            String id = request.getParameter("id");
            // 区域points
            String points = request.getParameter("points").split("\[")[1]
                    .split("\]")[0];
            String[] point = points.split("\},\{");
            AjaxJson js = new AjaxJson();
            // 取出每一个Point
            for (int i = 0; i < point.length; i++) {
                XnGpsPoint gps = new XnGpsPoint();
                gps.setMasterId(id);
                String[] lngandlat = point[i].split(",");
                for (int j = 0; j < lngandlat.length; j++) {
                    if (lngandlat[j].indexOf("lng") != -1) {
                        // point[i] 是经度
                        String lng = lngandlat[j].split(":")[1];
                        gps.setLng(Double.valueOf(lng));
                    } else if (lngandlat[j].indexOf("lat") != -1) {
                        // point[i] 是纬度
                        if (i != point.length - 1) {
                            String lat = lngandlat[j].split(":")[1];
                            gps.setLat(Double.valueOf(lat));
                        } else {
                            String lat = lngandlat[j].split(":")[1].split("\}")[0];
                            gps.setLat(Double.valueOf(lat));
                        }
                    }
                }
                try {
                    this.systemService.save(gps);
                    js.setSuccess(true);
                    js.setMsg("保存成功");
                } catch (Exception e) {
                    js.setSuccess(false);
                    js.setMsg("保存失败");
                }
            }
    
            return js;
        }

    4.判定

    Point2D.Double point = new Point2D.Double(Double.valueOf(sendlongitude), Double.valueOf(sendlatitude));  
            List<XnMaster> list = this.findByQueryString(" from XnMaster");
            List<Point2D.Double> pointList= new ArrayList<Point2D.Double>();  
            for (XnMaster master : list){  
                List<XnGpsPoint> gpsList = this.findByQueryString(" from XnGpsPoint where masterId='"+master.getId()+"' ");
                for (XnGpsPoint gps : gpsList){  
                    double polygonPoint_x=gps.getLng();  
                    double polygonPoint_y=gps.getLat();  
                    Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x,polygonPoint_y);  
                    pointList.add(polygonPoint); 
                }
                    Boolean flag = checkWithJdkGeneralPath(point,pointList);
                    if(flag){
                        maTelephone = master.getTelephone();
                        maName = master.getMasterName();
                        masterId = master.getId();
                        break;
                    }else{
                        a++;
                }  
            }
    
    
    
    
        /** 
         * 返回一个点是否在一个多边形区域内 
         * @param point 
         * @param polygon 
         * @return 
         */  
        private boolean checkWithJdkGeneralPath(Point2D.Double point, List<Point2D.Double> polygon) {  
            java.awt.geom.GeneralPath p = new java.awt.geom.GeneralPath();  
    
            Point2D.Double first = polygon.get(0);  
            p.moveTo(first.x, first.y);  
            polygon.remove(0);  
            for (Point2D.Double d : polygon) {  
                p.lineTo(d.x, d.y);  
            }  
    
            p.lineTo(first.x, first.y);  
    
            p.closePath();  
    
            return p.contains(point);  
    
        }  
  • 相关阅读:
    关键字--static
    java注解
    服务器、应用服务器、web服务器、容器
    进程和线程
    Tomcat7目录结构详解(非常详细)
    HTML小练习
    HTML学习笔记
    javaoo总结二
    javaoo总结一
    python核心-类-1
  • 原文地址:https://www.cnblogs.com/coriander/p/6266040.html
Copyright © 2011-2022 走看看