我正在使用react.js,我目前知道如何通过以下方式在多边形中打洞:
drawShape(google){
var entireMap = [
new google.maps.LatLng(-85.1054596961173, -180),
new google.maps.LatLng(85.1054596961173, -180),
new google.maps.LatLng(85.1054596961173, 180),
new google.maps.LatLng(-85.1054596961173, 180),
new google.maps.LatLng(-85.1054596961173, 0)];
var innerCoords = [
{lat: 28.745, lng: -70.579},
{lat: 29.570, lng: -67.514},
{lat: 27.339, lng: -66.668}
];
const poly = new google.maps.Polygon({
paths: [entireMap, innerCoords],
strokeColor: '#000000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#000000',
fillOpacity: 0.35
});
poly.setMap(google.map);
}
现在,我有一个包含 lng 和 lat 的属性列表。我不想将多边形作为孔,而是使用 lng 和 lat 将圆形作为孔。
到目前为止,我看到文档允许您单独创建圆圈:
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
但是,我希望这些圆是
entireMap
多边形内的“洞”。是否可以组合 entireMap
形状和圆形形状,或者我需要创建一个从多边形形状创建圆形的函数?
以下是我用来在地图中绘制多边形并在其中切出圆圈的组件。它是根据 React 编写的,但可以为其他库/框架提取解决方案
import { useEffect } from 'react'
import { useGoogleMap } from '@react-google-maps/api'
import { Map as MapConsts } from 'assets/consts'
const getCirclePath = (
center: google.maps.LatLng | google.maps.LatLngLiteral,
radius: number,
numParts = 512
) => {
const path = []
for (let i = 0; i < numParts; i += 1) {
path.push(
google.maps.geometry.spherical.computeOffset(
center,
radius,
(i * 360) / numParts
)
)
}
return path
}
type Props = {
center: google.maps.LatLng | google.maps.LatLngLiteral,
radius: number
}
function SearchRadius({ center, radius }) {
const map = useGoogleMap()
useEffect(() => {
// calculate inner circle path
const innerCircle = getCirclePath(center, radius)
const polygon = new google.maps.Polygon({
paths: [MapConsts.OUTER_BOUNDS, innerCircle],
strokeColor: '#000000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#000000',
fillOpacity: 0.35,
map,
})
return () => {
// remove polygon from map
polygon.setMap(null)
}
}, [center, radius])
return null
}
export default SearchRadius
这个解决方案需要几何库,补充一下,你可以在这里检查这个问题