Google maps api v3 rotate the polygon to a certain extent

I use Google maps to allow the user to draw a polygon, and then use the map APIs and some geometries to draw the minimum square that covers the drawn polygon at an angle of 16 degrees, i.e. a bounded square should bind the entire area of ​​the polygon AND should be rotated 16 degrees about the y axis.

Your help is much appreciated

Hi

+4
source share
2 answers

This is a difficult problem. I can describe the steps that will help you in most of the way:

Solution scheme

  • Get the map projection (map.getProjection ()) and convert the user polygon to the point plane using projection.fromLatLngToPoint.
  • Rotate the custom polygon to -16 degrees.
  • Calculate your bounding square / polygon for the newly rotated user.
  • Turn your polygon +16 degrees.
  • Convert the vertices of the polygons back to LatLng coordinates using projection.fromPointToLatLng

Resources:

+2
source

The following example shows how to rotate a polygon ( google.maps.Polygon class ).

Instruction:

  • draw a polygon
  • Click on the drawn polygon to rotate it.

 function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 13, center: { lat: 33.678, lng: -116.243 }, mapTypeId: google.maps.MapTypeId.TERRAIN }); var drawingManager = new google.maps.drawing.DrawingManager({ drawingMode: google.maps.drawing.OverlayType.POLYGON, drawingControl: true, drawingControlOptions: { position: google.maps.ControlPosition.TOP_CENTER, drawingModes: [ google.maps.drawing.OverlayType.POLYGON ] } }); drawingManager.setMap(map); google.maps.event.addListener(drawingManager, "overlaycomplete", function (event) { var polygon = event.overlay; google.maps.event.addListener(polygon, 'click', function (e) { autoRotatePolygon(polygon, 5); }); }); } function autoRotatePolygon(polygon, angle) { window.setInterval(function () { rotatePolygon(polygon, 5); }, 250); } function rotatePolygon(polygon,angle) { var map = polygon.getMap(); var prj = map.getProjection(); var origin = prj.fromLatLngToPoint(polygon.getPath().getAt(0)); //rotate around first point var coords = polygon.getPath().getArray().map(function(latLng){ var point = prj.fromLatLngToPoint(latLng); var rotatedLatLng = prj.fromPointToLatLng(rotatePoint(point,origin,angle)); return {lat: rotatedLatLng.lat(), lng: rotatedLatLng.lng()}; }); polygon.setPath(coords); } function rotatePoint(point, origin, angle) { var angleRad = angle * Math.PI / 180.0; return { x: Math.cos(angleRad) * (point.x - origin.x) - Math.sin(angleRad) * (point.y - origin.y) + origin.x, y: Math.sin(angleRad) * (point.x - origin.x) + Math.cos(angleRad) * (point.y - origin.y) + origin.y }; } 
 html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } 
 <div id="map"></div> <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=drawing"></script> 

Jsfiddle

+1
source

Source: https://habr.com/ru/post/1411544/


All Articles