簡體   English   中英

如何使用Google Maps Javascript API圖形庫復制和縮放Shape?

[英]How to copy and scale a Shape using the Google Maps Javascript API drawing library?

我正在我的React應用程序中創建一個Google Map,我希望用戶能夠繪制形狀,其附加功能是一旦用戶完成繪制形狀,則必須將其他形狀添加到輪廓中,如下圖所示:

用戶繪制的形狀:

在此處輸入圖片說明

我打算在用戶完成繪制形狀后立即添加功能:

在此處輸入圖片說明

我正在使用Google地圖的圖形庫,如下所示: https : //developers.google.com/maps/documentation/javascript/examples/drawing-tools

這是我正在使用的相關代碼:

    // When a circle is drawn
    google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
      let tempCirc = new google.maps.Circle({ 
        radius: circle.getRadius()*2, 
        center: circle.getCenter(),
        editable: true,
        map: map
      })
    });

   // When a rectangle is drawn
   google.maps.event.addListener(drawingManager, 'rectanglecomplete', function(rect) {
      let tempRect = new google.maps.Rectangle({
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: '#FF0000',
          fillOpacity: 0.35,
          map: map,
          editable: true,
          draggable: true
        })

      rectangle.setBounds(
        new google.maps.LatLngBounds(
          new google.maps.LatLng(
            rect.getBounds().getSouthWest().lat() - .005, 
            rect.getBounds().getSouthWest().lng() - .005*2
          ),
          new google.maps.LatLng(
            rect.getBounds().getNorthEast().lat() + .005, 
            rect.getBounds().getNorthEast().lng() + .005*2
          ),
        )
      )
    });

    // When a polygon is drawn
    google.maps.event.addListener(drawingManager, 'polygoncomplete', function(poly) {
      // What can I do here?
    });

如果在Google地圖上還有其他方法可以做到這一點,請也告訴我。

感謝@MrUpsidown的建議,我得以使用google.maps.geometry.spherical命名空間中的interpolate()方法。

通過提供大於1的分數,我能夠獲得點以形成外部多邊形。 該方法適用於沒有孔的相當簡單的多邊形。 希望它可以幫助某人。

// getCenter() for Polygon
google.maps.Polygon.prototype.getCenter = function(){
  var arr = this.getPath().getArray()
  , distX = 0, distY = 0
  , len = arr.length

  arr.forEach(function (element, index) { 
    distX+= element.lat()
    distY+= element.lng()
  });

  return new google.maps.LatLng(distX/len, distY/len);
}

google.maps.event.addListener(drawingManager, 'polygoncomplete', function(poly) {
  let polyCenter = poly.getCenter()
  , innerShapePoints = poly.getPath().getArray()
  , outerShapePoints = []

  outerShapePoints = innerShapePoints.map(point => {
    return google.maps.geometry.spherical.interpolate(polyCenter, point, 1.5)
  })

  let outerPolygon = new google.maps.Polygon({
    strokeColor: '#0000FF',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#0000FF',
    fillOpacity: 0.35,
    map: map,
    editable: true,
    suppressUndo: true,
    draggable: true,
    path: outerShapePoints
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM