Search code examples
javascriptgeometryleafletgeo

Rotate leaflet Polyline/Rectangle


I'am trying to rotate Leaflet Rectangle using code from this question.

rotatePoints (center, points, yaw) {
  const res = []
  const angle = yaw * (Math.PI / 180)
  for (let i = 0; i < points.length; i++) {
  const p = points[i]
  // translate to center
  const p2 = new LatLng(p.lat - center.lat, p.lng - center.lng)
  // rotate using matrix rotation
  const p3 = new LatLng(Math.cos(angle) * p2.lat - Math.sin(angle) * p2.lng, Math.sin(angle) * p2.lat + Math.cos(angle) * p2.lng)
  // translate back to center
  const p4 = new LatLng(p3.lat + center.lat, p3.lng + center.lng)
  // done with that point
  res.push(p4)
}
return res
}

The problem is that the rectangle is skewed while rotating. Any ideas how to optimize this function?

Fixed Final code:

rotatePoints (center, points, yaw) {
  const res = []
  const centerPoint = map.latLngToLayerPoint(center)
  const angle = yaw * (Math.PI / 180)
  for (let i = 0; i < points.length; i++) {
    const p = map.latLngToLayerPoint(points[i])
    // translate to center
    const p2 = new Point(p.x - centerPoint.x, p.y - centerPoint.y)
    // rotate using matrix rotation
    const p3 = new Point(Math.cos(angle) * p2.x - Math.sin(angle) * p2.y, Math.sin(angle) * p2.x + Math.cos(angle) * p2.y)
    // translate back to center
    let p4 = new Point(p3.x + centerPoint.x, p3.y + centerPoint.y)
    // done with that point
    p4 = map.layerPointToLatLng(p4)
    res.push(p4)
  }
return res
}

Solution

  • What is "rectangle" on sphere? It is result of applying of current projection to such coordinates that their image on the map/screen form rectangle. Note that lat-long coordinates are not ought to be equal for every rectangle side (for example, longitude for equator-aligned rectangle will differ for top and bottom point in the most of usual projections)

    So to to get good-looking rectangle in map, you need to rotate vertices in screen coordinates, and make back-projection into lat-long space.