Openlayers測定機能を実現する

16490 ワード

本論文の実例はOpenlayers測定を実現する具体的なコードを共有しています。
会社のプロジェクトがopenlayersまで使う必要があるので、openlayersを勉強し始めました。その中の一つは測定機能を使う必要があります。

<!DOCTYPE html>
<html>
 
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title></title>
 <link rel="stylesheet" href="./ol.css" type="text/css">
 <script src="./ol.js" type="text/javascript"></script>
 <link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">
 <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
 <script src="https://cdn.bootcss.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
 <style type="text/css">
  #map {
   width: 100%;
   height: 100%;
   position: absolute;
  }
 
  #menu {
   float: left;
   position: absolute;
   bottom: 50px;
   right: 30px;
   z-index: 2000;
  }
 
  .checkbox {
   left: 20px;
  }
 
  /**
  *         
  */
  .tooltip {
   position: relative;
   background: rgba(0, 0, 0, 0.5);
   border-radius: 4px;
   color: white;
   padding: 4px 8px;
   opacity: 0.7;
   white-space: nowrap;
  }
 
  .tooltip-measure {
   opacity: 1;
   font-weight: bold;
  }
 
  .tooltip-static {
   background-color: #ffffff;
   color: black;
   border: 1px solid white;
  }
 
  .tooltip-measure:before,
  .tooltip-static:before {
   border-top: 6px solid rgba(0, 0, 0, 0.5);
   border-right: 6px solid transparent;
   border-left: 6px solid transparent;
   content: "";
   position: absolute;
   bottom: -6px;
   margin-left: -7px;
   left: 50%;
  }
 
  .tooltip-static:before {
   border-top-color: #ffffff;
  }
 
  #scalebar {
   float: left;
   margin-bottom: 10px;
  }
 </style>
 
</head>
 
<body>
 <div id="map">
  <div id="menu">
   <label>      </label>
   <select id="type">
    <option value="length">  </option>
    <option value="area">  </option>
   </select>
   <label class="checkbox label"><input type="checkbox" id="geodesic" />      </label>
  </div>
 </div>
 <div id="scalebar"></div>
 <script type="text/javascript">
  $(function () {
   //  
   var format = 'image/png';
   var bounds = [73.441277, 18.159829,
    135.08693, 53.561771];//  
 
   //      ( )
   var ImageMap = new ol.layer.Tile({
    source: new ol.source.TileWMS({
     ratio: 1,
     //     url
     url: 'http://localhost:8080/geoserver/China_Test/wms',
     //      
     params: {
      'FORMAT': format,
      'VERSION': '1.1.0',
      STYLES: '',
      //    
      LAYERS: 'China_Test:C_Test',
     }
    })
   });
 
   //      
   var projection = new ol.proj.Projection({
    code: 'EPSG:4326',//    
    units: 'degrees',
    axisOrientation: 'neu'
   });
 
   //            
   var map = new ol.Map({
    //            
    controls: ol.control.defaults({
     attribution: false
    }).extend([
     new ol.control.FullScreen(),//    
    ]),
    //       
    target: 'map',
    //    
    layers: [
     //    
     ImageMap
    ],
    //    
    view: new ol.View({
     //    
     projection: projection,
     center: [102.73333, 25.05], //      
     minZoom: 3,
     zoom: 5, //    
    }),
   });
 
   //       
   var source = new ol.source.Vector();
   //      
   var vector = new ol.layer.Vector({
    source: source,
    style: new ol.style.Style({
     fill: new ol.style.Fill({
      color: 'rgba(255,255,255,0.2)'
     }),
     stroke: new ol.style.Stroke({
      color: '#e21e0a',
      width: 2
     }),
     image: new ol.style.Circle({
      radius: 5,
      fill: new ol.style.Fill({
       color: '#ffcc33'
      })
     })
    })
   });
   //           
   map.addLayer(vector);
 
   //       
   var scaleLineControl = new ol.control.ScaleLine({
    units: 'metric',
    target: 'scalebar',
    className: 'ol-scale-line'
   });
   map.addControl(scaleLineControl);
 
 
   //         
   var mousePositionControl = new ol.control.MousePosition({
    coodrdinateFormat: ol.coordinate.createStringXY(4),//    
    //       
    projection: new ol.proj.Projection({
     code: 'EPSG:4326',//    
     units: 'degrees',
     axisOrientation: 'neu'
    }),
    //className:'tip',
    target: document.getElementById('tip'),//             
    undefinedHTML: '&nbsp;'//       
   });
 
   //        
   map.addControl(mousePositionControl);
 
   //        
   var overviewMapControl = new ol.control.OverviewMap({
    //                  
    layers: [
     new ol.layer.Tile({
      source: new ol.source.OSM({
       'url': 'http://{a-c}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png'
      })
     })
    ],
    collapseLabel: '\u00BB',
    lable: '\u00AB',
    collapsed: false,
   });
   //    
   map.addControl(overviewMapControl);
 
   //    WGS84    
   var wgs84Sphere = new ol.Sphere(6378137);
   //            
   var sketch = new ol.Feature();
   //           
   var helpTooltipElement;
   //            
   var helpTooltip;
   //           
   var measureTooltipElement;
   //            
   var measureTooltip;
   //            
   var continuePolygonMsg = '          ';
   //           
   var continueLineMsg = '         ';
 
   //         
   var pointerMoveHandler = function (evt) {
    //Indicates if the map is currently being dragged. 
    //Only set for POINTERDRAG and POINTERMOVE events. Default is false.
    //            
    if (evt.dragging) {
     return;
    }
    //      
    var helpMsg = '    ';
 
    if (sketch) {
     //           
     var geom = sketch.getGeometry();
     //               ,                    
     if (geom instanceof ol.geom.Polygon) {
      helpMsg = continuePolygonMsg;
     } else if (geom instanceof ol.geom.LineString) {
      helpMsg = continueLineMsg;
     }
    }
    //                   
    helpTooltipElement.innerHTML = helpMsg;
    //           
    helpTooltip.setPosition(evt.coordinate);
    //             
    $(helpTooltipElement).removeClass('hidden');
   };
 
   //  pointermove  
   map.on('pointermove', pointerMoveHandler);
 
   //                        
   $(map.getViewport()).on('mouseout', function () {
    $(helpTooltipElement).addClass('hidden');
   });
 
   //         
   var geodesicCheckbox = document.getElementById('geodesic');
   //    
   var typeSelect = document.getElementById('type');
   //           
   var draw;
 
   //            
   function addInteraction() {
    //            
    var type = typeSelect.value == 'area' ? 'Polygon' : 'LineString';
    //           
    draw = new ol.interaction.Draw({
     //      
     source: source,
     //    
     type: type,
     //  
     style: new ol.style.Style({
      fill: new ol.style.Fill({
       color: 'rgba(255,255,255,0.2)'
      }),
      stroke: new ol.style.Stroke({
       color: 'rgba(0,0,0,0.5)',
       lineDash: [10, 10],
       width: 2
      }),
      image: new ol.style.Circle({
       radius: 5,
       stroke: new ol.style.Stroke({
        color: 'rgba(0,0,0,0.7)'
       }),
       fill: new ol.style.Fill({
        color: 'rgba(255,255,255,0.2)'
       })
      })
     })
    });
    //             
    map.addInteraction(draw);
 
    //       
    createMeasureTooltip();
    //       
    createHelpTooltip();
 
    //        
    var listener;
    //               
    var count = 0;
    //      
    draw.on('drawstart', function (evt) {
     //The feature being drawn.
     sketch = evt.feature;
     //      
     var tooltipCoord = evt.coordinate;
     //       change  
     //Increases the revision counter and dispatches a 'change' event.
 
     listener = sketch.getGeometry().on('change', function (evt) {
      //The event target.
      //         
      var geom = evt.target;
      //        ,         
      var output;
      if (geom instanceof ol.geom.Polygon) {
       map.removeEventListener('singleclick');
       map.removeEventListener('dblclick');
       //        
       output = formatArea(geom);
       //           
       tooltipCoord = geom.getInteriorPoint().getCoordinates();
      } else if (geom instanceof ol.geom.LineString) {
       //        
       output = formatLength(geom);
       //              
       tooltipCoord = geom.getLastCoordinate();
      }
 
      //                  
      measureTooltipElement.innerHTML = output;
      //             
      measureTooltip.setPosition(tooltipCoord);
     });
 
     //      
     map.on('singleclick', function (evt) {
      //             ,                 
      measureTooltip.setPosition(evt.coordinate);
      //        ,                
      if (count == 0) {
       measureTooltipElement.innerHTML = "  ";
      }
      //             
      var point = new ol.geom.Point(evt.coordinate);
      //              
      source.addFeature(new ol.Feature(point));
      //          ,        
      measureTooltipElement.className = 'tooltip tooltip-static';
      //       
      createMeasureTooltip();
      //      
      count++;
     });
 
     //      
     map.on('dblclick', function (evt) {
      var point = new ol.geom.Point(evt.coordinate);
      source.addFeature(new ol.Feature(point));
     });
    }, this);
    //      
    draw.on('drawend', function (evt) {
     count = 0;
     //          
     measureTooltipElement.className = 'tooltip tooltip-static';
     //     
     measureTooltip.setOffset([0, -7]);
     //      
     sketch = null;
     //        
     measureTooltipElement = null;
     //       
     createMeasureTooltip();
     //      
     ol.Observable.unByKey(listener);
     //        
     map.removeEventListener('singleclick');
    }, this);
   }
   //       
   function createHelpTooltip() {
    //              
    if (helpTooltipElement) {
     helpTooltipElement.parentNode.removeChild(helpTooltipElement);
    }
    //         div
    helpTooltipElement = document.createElement('div');
    //           
    helpTooltipElement.className = 'tooltip hidden';
    //             
    helpTooltip = new ol.Overlay({
     element: helpTooltipElement,
     offset: [15, 0],
     positioning: 'center-left'
    });
    //                
    map.addOverlay(helpTooltip);
   }
   //       
   function createMeasureTooltip() {
    //        div
    measureTooltipElement = document.createElement('div');
    measureTooltipElement.setAttribute('id', 'lengthLabel');
    //           
    measureTooltipElement.className = 'tooltip tooltip-measure';
    //             
    measureTooltip = new ol.Overlay({
     element: measureTooltipElement,
     offset: [0, -15],
     positioning: 'bottom-center'
    });
    //                
    map.addOverlay(measureTooltip);
   }
   //             
   typeSelect.onchange = function () {
    //         
    map.removeInteraction(draw);
    //      
    addInteraction();
   };
 
   //       
   var formatLength = function (line) {
    //      
    var length;
    //            ,       
    if (geodesicCheckbox.checked) {
     //     
     var coordinates = line.getCoordinates();
     //     0
     length = 0;
     //         
     var sourceProj = map.getView().getProjection();
     //        
     for (var i = 0; i < coordinates.length - 1; i++) {
      //    
      var c1 = ol.proj.transform(coordinates[i], sourceProj, 'EPSG:4326');
      //    
      var c2 = ol.proj.transform(coordinates[i + 1], sourceProj, 'EPSG:4326');
      //          
      //Returns the distance from c1 to c2 using the haversine formula.
      length += wgs84Sphere.haversineDistance(c1, c2);
     }
    } else {
     //      
     length = Math.round(line.getLength() * 100) / 100;
    }
    //      
    var output;
    //      1000,   km  ,    m  
    if (length > 1000) {
     output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km'; //   KM  
    } else {
     output = (Math.round(length * 100) / 100) + ' ' + 'm'; //m   
    }
    return output;
   };
 
   //       
   var formatArea = function (polygon) {
    //      
    var area;
    //            ,       
    if (geodesicCheckbox.checked) {
     //       
     var sourceProj = map.getView().getProjection();
     var geom = polygon.clone().transform(sourceProj, 'EPSG:4326');
     //         
     var coordinates = geom.getLinearRing(0).getCoordinates();
     //      
     area = Math.abs(wgs84Sphere.geodesicArea(coordinates));
    } else {
     //      
     area = polygon.getArea();
    }
    //      
    var output;
    //     10000 ,       ,      
    if (area > 10000) {
     output = (Math.round(area / 1000000 * 100) / 100) + ' ' + 'km<sup>2</sup>';
    } else {
     output = (Math.round(area * 100) / 100) + ' ' + 'm<sup>2</sup>';
    }
    return output;
   };
   //        
   addInteraction();
  });
 </script>
</body>
 
</html>
効果図:

PS:ここで呼び出したレイヤーは、geoserverを使ってリリースされたコンビネーションレイヤーです。自分で定義できます。
ソースコードアドレス:測定例
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。