SoFunction
Updated on 2025-03-10

Implement angle measurement function based on openlayers

Based on the measurement function of openlayers, the official website provides length measurement and angle measurement, but there is no angle measurement. Here I will write about the angle measurement function based on openlayers. The main methods are as follows:

var formatAngle = function (line) {
  var coordinates = ();
  var angle=0;
  var sourceProj = ().getProjection();
  for (var i =0, ii =  - 1; i < ii; ++i) {
    var c1 = (coordinates[i], sourceProj, 'EPSG:4326');
    var c2 = (coordinates[i + 1], sourceProj, 'EPSG:4326');
    var c3=0
    //When drawing two or more points, pass the value of c1 to C3 and the value of C2 to C1    if(i>=1){
      c3=(coordinates[i-1], sourceProj, 'EPSG:4326');
      var disa=(c3, c1);
      var disb=(c1, c2);
      var disc=(c2, c3);
      // Since double-clicking at the end of the drawing will cause c1=c2, thus disb=0, and the denominator cannot be zero, resulting in angle=NAN value, so the previous value of the double-click needs to be taken.      //When there are more than three points, an angle is formed, and the angle needs to be measured and output.      if(disb===0&&i>=2){
        c1 = (coordinates[i-1], sourceProj, 'EPSG:4326');
        c2 = (coordinates[i], sourceProj, 'EPSG:4326');
        c3 = (coordinates[i-2], sourceProj, 'EPSG:4326');
        disa=(c3, c1);
        disb=(c1, c2);
        disc=(c2, c3);
      }
      var cos=(disa*disa+disb*disb-disc*disc)/(2*disa*disb);  //Use the cosine theorem formula to calculate the cos value      angle=(cos)*180/;  //Finish the inverse cosine value, obtain the radian system, and turn the radian value into the angle value      angle=(2)+"Spend";  //For the angle of calculation completion, retain two decimal places      // Since double-clicking at the end of the drawing will cause c1=c2, thus disb=0, and the denominator cannot be zero, resulting in angle=NAN value, so the previous value of the double-click needs to be taken.      //When there are only two points, it is just a line and does not form an angle. You need to prompt to continue drawing.      if(disb===0&&i<2){
        angle="Please continue drawing to form angles";
      }
    }
    //When just drawing a point, the prompt is to continue drawing.    else{
      angle="Please continue drawing to form angles";
    }
  }
  var output;
  output=angle;
  return output;//return};

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.