在谷歌地图javascript中通过功能构建多个多边形

时间:2014-12-03 08:09:02

标签: javascript google-maps-api-3

我想在谷歌地图中构建很多区域,并且每个区域都定义了一个多边形。 如果我一个接一个地做它没有问题(在initialize func中):

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);

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

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

任何帮助,为什么,我怎么称错了?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

扩展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;
}