Openlayers測定距離と面積の実現方法

15707 ワード

本論文の実例はOpenlayers測定距離と面積の具体的なコードを共有しています。
1、地図測定機能
一般的な地図の測量機能は主に二つの面に現れます。一つは距離を測ること、一つは面積を測ることです。面積の測定はマウスの描く範囲によって、地理座標系の変換によって実際の面積の大きさを計算します。距離の測定はマウスの地図上に描く点によって、リアルタイムで2点の間の実際の距離を計算します。次にOpenlayers 3でこの機能を実現します。
2、コード実現

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title></title>
 <script src="../lib/ol/ol.js"></script>
 <link href="../css/ol.css" rel="stylesheet" />
 <script src="../lib/jquery/jquery-1.8.2.js"></script>
 <link href="../css/bootstrap.min.css" rel="stylesheet" />
 <script src="../lib/bootstrap/bootstrap.min.js"></script>
 <style type="text/css">
  #map {
   width: 100%;
   height: 100%;
   position: absolute;
  }
 
  #menu {
   float: left;
   position: absolute;
   bottom: 10px;
   left: 10px;
   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>
 <script type="text/javascript">
  $(function () {
   //     
   var map = new ol.Map({
    target: 'map',
    layers: [
     new ol.layer.Tile({
      source:new ol.source.OSM()
     })
    ],
    view: new ol.View({
     center: new ol.proj.fromLonLat([114.4250, 23.0890]),
     zoom: 18,
     maxZoom: 20
    })
   });
 
   //       
   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);
 
 
   //    WGS84    
   var wgs84Sphere = new ol.Sphere(6378137);
   //            
   var sketch = new ol.Feature();
   //           
   var helpTooltipElement;
   //            
   var helpTooltip;
   //           
   var measureTooltipElement;
   //            
   var measureTooltip;
   //            
   var continuePolygonMsg = 'Click to continue drawing the polygon';
   //           
   var continueLineMsg = 'Click to continue drawing the line';
 
   //         
   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 = 'Click to start drawing';
 
    if (sketch) {
     //Get the feature's default geometry. 
     //A feature may have any number of named geometries.
     //           
     var geom = sketch.getGeometry();
     //               ,                    
     //               ,                    
     if (geom instanceof ol.geom.Polygon) {
      helpMsg = continuePolygonMsg;
     } else if (geom instanceof ol.geom.LineString) {
      helpMsg = continueLineMsg;
     }
    }
    //                   
    helpTooltipElement.innerHTML = helpMsg;
    //           
    //The coordinate in view projection corresponding to the original browser event.
    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);
       //Return an interior point of the polygon.
       //           
       tooltipCoord = geom.getInteriorPoint().getCoordinates();
      } else if (geom instanceof ol.geom.LineString) {
       //        
       output = formatLength(geom);
       //Return the last coordinate of the geometry.
       //              
       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';
     //Set the offset for this overlay.
     //     
     measureTooltip.setOffset([0, -7]);
     //      
     sketch = null;
     //        
     measureTooltipElement = null;
     //       
     createMeasureTooltip();
     //Removes an event listener using the key returned by on() or once().
     //      
     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) {
     //Return the coordinates of the linestring.
     //     
     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 {
     //Return the length of the linestring on projected plane.
     //      
     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();
     //Make a complete copy of the geometry.
     //Transform each coordinate of the geometry from one coordinate reference system to another. 
     //The geometry is modified in place. For example, a line will be transformed to a line and a circle to a circle.
     //If you do not want the geometry modified in place, first clone() it and then use this function on the clone.
     //              
     var geom = polygon.clone().transform(sourceProj, 'EPSG:4326');
     //Return the Nth linear ring of the polygon geometry. 
     //Return null if the given index is out of range. 
     //The exterior linear ring is available at index 0 and the interior rings at index 1 and beyond.
     //         
     var coordinates = geom.getLinearRing(0).getCoordinates();
     //Returns the geodesic area for a list of coordinates.
     //      
     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>
</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"><input type="checkbox" id="geodesic" />      </label>
  </div>
 </div>
 <div id="scalebar"></div>
</body>
</html>
3、結果の展示
距離を測る

面積を測る

また、大地で測定したチェックボックスをチェックして、球面距離と面積の測定を行うこともできます。
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。