Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps Rotate Polygon

After drawing a Polygon shape on the map. I would like to change what direction the polygon is pointing when the map is refreshed by rotating around one of the points of the polygon. For example point the polygon in the direction of 90 degrees rotating around my first polygon point (code shown below). Can anyone provide any code examples of this working? I have seen some similar posts however examples given appear over complicated.

poly = new google.maps.Polygon({
  strokeWeight: 3,
  fillColor: '#5555FF'
});
poly.setMap(map);
poly.setPaths(new google.maps.MVCArray([path]));

  var triangleCoords = [
  new google.maps.LatLng(51.5087, -0.1277),
  new google.maps.LatLng(51.5387, -0.1077),
  new google.maps.LatLng(51.5387, -0.1477),
  new google.maps.LatLng(51.5087, -0.1277)
];

// Construct the polygon
triangle = new google.maps.Polygon({
  paths: triangleCoords,
  strokeColor: "#FF0000",
  strokeOpacity: 0.8,
  strokeWeight: 2,
  fillColor: "#FF0000",
  fillOpacity: 0.8
});
triangle.setMap(map);

google.maps.event.addListener(map, 'click', triangle);

}
like image 539
user1841890 Avatar asked Nov 22 '12 11:11

user1841890


2 Answers

The following example demonstrates how to rotate a polygon

Note: the rotation is performed around the first point

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5,
    center: {lat: 24.886, lng: -70.268},
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  // Define the LatLng coordinates for the polygon's path.
  var triangleCoords = [
    {lat: 25.774, lng: -80.190},
    {lat: 18.466, lng: -66.118},
    {lat: 32.321, lng: -64.757},
    {lat: 25.774, lng: -80.190}
  ];

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);
  
  //rotate a polygon
  document.getElementById('btnRotate').onclick = function() {
        rotatePolygon(bermudaTriangle, 90);
  };
}


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%;
}

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}
<div id="floating-panel">
  <input type="button" id="btnRotate" value="Rotate 90"></div>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>

JSFiddle

like image 143
Vadim Gremyachev Avatar answered Sep 20 '22 12:09

Vadim Gremyachev


You might want to look at something like Mike Williams' eshapes library. It was written originally for the Google Maps API v2, but this page demonstrates the version that I ported to the Google Maps API v3.

example

proof of concept fiddle

code snippet;

var map = null;
var triangle, angle, point;

function initMap() {
  point = new google.maps.LatLng(44, -80);

  var myOptions = {
    zoom: 8,
    center: point,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map"),
    myOptions);

  angle = 0;
  // === Triangle ===
  triangle = google.maps.Polyline.RegularPoly(point, 30000, 3, angle, "#ff0000", 8, 1);
  triangle.setMap(map);
  google.maps.event.addListener(triangle, "click", rotateTriangle);
}
google.maps.event.addDomListener(window, 'load', initMap);

function rotateTriangle() {
  triangle.setMap(null);
  angle += 90;
  if (angle >= 360) angle -= 360;
  triangle = google.maps.Polyline.RegularPoly(point, 30000, 3, angle, "#ff0000", 8, 1);
  triangle.setMap(map);
  google.maps.event.addListener(triangle, "click", rotateTriangle);
}

// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/   
// http://econym.org.uk/gmap/

// From v3_eshapes.js:
// EShapes.js
//
// Based on an idea, and some lines of code, by "thetoy" 
//
//   This Javascript is provided by Mike Williams
//   Community Church Javascript Team
//   http://www.bisphamchurch.org.uk/   
//   http://econym.org.uk/gmap/
//
//   This work is licenced under a Creative Commons Licence
//   http://creativecommons.org/licenses/by/2.0/uk/
//
// Version 0.0 04/Apr/2008 Not quite finished yet
// Version 1.0 10/Apr/2008 Initial release
// Version 3.0 12/Oct/2011 Ported to v3 by Lawrence Ross

google.maps.Polyline.RegularPoly = function(point, radius, vertexCount, rotation, colour, weight, opacity, opts) {
  rotation = rotation || 0;
  var tilt = !(vertexCount & 1);
  return google.maps.Polyline.Shape(point, radius, radius, radius, radius, rotation, vertexCount, colour, weight, opacity, opts, tilt)
}
google.maps.Polyline.Shape = function(point, r1, r2, r3, r4, rotation, vertexCount, colour, weight, opacity, opts, tilt) {
  if (!colour) {
    colour = "#0000FF";
  }
  if (!weight) {
    weight = 4;
  }
  if (!opacity) {
    opacity = 0.45;
  }
  var rot = -rotation * Math.PI / 180;
  var points = [];
  var latConv = google.maps.geometry.spherical.computeDistanceBetween(point, new google.maps.LatLng(point.lat() + 0.1, point.lng())) * 10;
  var lngConv = google.maps.geometry.spherical.computeDistanceBetween(point, new google.maps.LatLng(point.lat(), point.lng() + 0.1)) * 10;
  var step = (360 / vertexCount) || 10;

  var flop = -1;
  if (tilt) {
    var I1 = 180 / vertexCount;
  } else {
    var I1 = 0;
  }
  for (var i = I1; i <= 360.001 + I1; i += step) {
    var r1a = flop ? r1 : r3;
    var r2a = flop ? r2 : r4;
    flop = -1 - flop;
    var y = r1a * Math.cos(i * Math.PI / 180);
    var x = r2a * Math.sin(i * Math.PI / 180);
    var lng = (x * Math.cos(rot) - y * Math.sin(rot)) / lngConv;
    var lat = (y * Math.cos(rot) + x * Math.sin(rot)) / latConv;

    points.push(new google.maps.LatLng(point.lat() + lat, point.lng() + lng));
  }
  return (new google.maps.Polyline({
    path: points,
    strokeColor: colour,
    strokeWeight: weight,
    strokeOpacity: opacity
  }))
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<b>Click triangle's border to rotate it.</b>
<div id="map"></div>
like image 44
geocodezip Avatar answered Sep 19 '22 12:09

geocodezip