在Google Maps JavaScript中按功能构建多个多边形

building multiple polygons by function in google maps javascript

本文关键字:构建 多边形 功能 Google Maps JavaScript      更新时间:2023-09-26

我想在谷歌地图中构建很多区域,并用多边形定义每个区域。如果我一个接一个地做,它可以正常工作(在初始化函数内):

name = new google.maps.Polygon({
           paths: coords,
           strokeColor: 'darkgreen',
           strokeOpacity: 0.3,
           strokeWeight: 1,
           fillOpacity: 0.05
       });
//some event
//highlights polygon when mouseover
google.maps.event.addListener(name, 'mouseover', function () {
name.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
//then displaying it on the map:
name.setMap(map);

现在我想有一个函数来输入坐标来构建多边形,就像这样。但是只是调用该函数会阻止渲染其他多边形,所以我知道调用它有问题:

iName = new drawPolygon(polyName, coords);
iName.setMap(map);

该函数如下所示:

function drawPolygon(polyName, coords) {
       polyName =  new google.maps.Polygon({
           paths: coords,
           strokeColor: 'darkgreen',
           strokeOpacity: 0.3,
           strokeWeight: 1,
           //fillColor: 'green',
           fillOpacity: 0.05
       });

       //highlights polygon when mouseover
       google.maps.event.addListener(polyName, 'mouseover', function () {
           polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
       });
   }

关于为什么的任何帮助,我怎么说错了?

drawPolygon 没有返回语句。它返回null . null没有 .setMap 方法。

扩展 geocodezip 的答案,只需向函数添加一个 return 语句即可。

function drawPolygon(polyName, coords) {
       polyName =  new google.maps.Polygon({
           paths: coords,
           strokeColor: 'darkgreen',
           strokeOpacity: 0.3,
           strokeWeight: 1,
           fillOpacity: 0.05
       });

       //highlights polygon when mouseover
       google.maps.event.addListener(polyName, 'mouseover', function () {
           polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
       });
       return polyName;
}

在这种情况下,我也倾向于不费心将polyName作为参数传递到函数中。 在调用 drawPolygon 之前,您不必费心向我们展示创建 polyName 变量的代码。 但我假设你没有用它做任何特别聪明的事情,需要你这样做。

所以重构:

iName = new drawPolygon(coords);
iName.setMap(map);
function drawPolygon(coords) {
       var polyName =  new google.maps.Polygon({
           paths: coords,
           strokeColor: 'darkgreen',
           strokeOpacity: 0.3,
           strokeWeight: 1,
           fillOpacity: 0.05
       });

       //highlights polygon when mouseover
       google.maps.event.addListener(polyName, 'mouseover', function () {
           polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
       });
       return polyName;
}