Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

javascript - rotate polygon around point in leaflet map

I have an issue, in my leaflet map I've created a triangle from polygon:

var polygon = L.polygon([ 
    [parseFloat(decimal_lat),parseFloat(decimal_lon)], 
    [parseFloat(decimal_lat) + 1, parseFloat(decimal_lon) - 1], 
    [parseFloat(decimal_lat) + 1, parseFloat(decimal_lon) + 1] ],       
    {
            color:'green'
    });
polygon.addTo(map);

and I want to rotate this polygon around Point[decimal_lon, decimal_lat]. But I'm not able to solve it..
I've created DEMO, where I'm rotating polynom the same I want to rotate my triangle (polygon) to show you my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way to do it is through matrix rotation. https://en.wikipedia.org/wiki/Rotation_matrix. You want to translate the point to the center then apply the rotation, then translate it back.

This is what the end of your code would look like.

  //changing polyline with slider but I want to change polygon there
  range_yaw.onchange = function() {
    var yawAngle = (parseFloat(range_yaw.value) / (819 / 360) + 90)
    // line
    var center = [decimal_lat, decimal_lon]
    var end = [decimal_lat + 2, decimal_lon + 2]
    var pointListRotated = rotatePoints(center, [center, end], yawAngle)
    polyline.setLatLngs(pointListRotated);
    // polygon
    var polygonPoints = [
      center,
      [center[0] + 1, center[1] - 1],
      [center[0] + 1, center[1] + 1]
    ]
    polygonRotated = rotatePoints(center, polygonPoints, yawAngle)
    polygon.setLatLngs(polygonRotated)
  };

  //
  // rotate a list of points in [lat, lng] format about the center.
  //
  function rotatePoints(center, points, yaw) {
    var res = []
    var angle = yaw * (Math.PI / 180)
    for(var i=0; i<points.length; i++) {
      var p = points[i]
      // translate to center
      var p2 = [ p[0]-center[0], p[1]-center[1] ]
      // rotate using matrix rotation
      var p3 = [ Math.cos(angle)*p2[0] - Math.sin(angle)*p2[1], Math.sin(angle)*p2[0] + Math.cos(angle)*p2[1]]
      // translate back to center
      var p4 = [ p3[0]+center[0], p3[1]+center[1]]
      // done with that point
      res.push(p4)
    }
    return res
  }

Here is a DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...