google maps api v3 rotate a polygon by certain degree

岁酱吖の 提交于 2019-12-05 16:57:43

This is a complicated problem. I can outline the steps to get you most of the way there:

Solution Outline

  1. Get the map projection (map.getProjection()) and convert the user polygon to the point plane using projection.fromLatLngToPoint.
  2. Rotate the user polygon -16 degrees.
  3. Calculate your bounding square/polygon for the newly rotated user one.
  4. Rotate your polygon by +16 degrees.
  5. Convert your polygon vertices back to LatLng coordinates using projection.fromPointToLatLng

Resources:

The following example demonstrates 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!