Javascript Google 地图 API geometry 多边形函数

Javascript Google Maps API geometry polygon function

我有一个非常复杂的 Google 地图构建,我刚刚花了一个小时提炼到我的问题的基本部分。

地图上有一个地区的标记(实际上我有几十个)。每个区域都有多边形点。用户单击区域标记,然后可以单击信息窗口中的按钮以在该区域内进行搜索。单击按钮后,我想在地图上设置多边形,检查多边形是否顺时针定义并将地图边界设置为多边形。

我的完整脚本中还有其他调用 get_polygon_boundary 的函数,一切正常。但是这个按钮 returns google.maps.geometry 是未定义的,我不知道为什么。

我试过用 initialize 放置所有函数,但没有成功。

有人能帮忙吗?

// google
var google, map, iw;
var a_mks = [];

// ==========================================

function initialize() {

  //create map
  map = new google.maps.Map(
    document.getElementById("map"), {
      center: new google.maps.LatLng(25.774, -80.190),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.TERRAIN,
      zoomControl: true
    });

  // add getbounds to google maps functions
  google.maps.Polygon.prototype.getBounds = function() {
    var b = new google.maps.LatLngBounds();
    var paths = this.getPaths();
    var path;
    for (var i = 0; i < paths.getLength(); i++) {
      path = paths.getAt(i);
      for (var ii = 0; ii < path.getLength(); ii++) {
        b.extend(path.getAt(ii));
      }
    }
    return b;
  }

  regions = [{
    cat: 'Region',
    l: 'Bermuda Triangle',
    lat: 25.774,
    lng: -80.190,
    zoom: 9,
    poly: [{
      lat: 25.774,
      lng: -80.190
    }, {
      lat: 18.466,
      lng: -66.118
    }, {
      lat: 32.321,
      lng: -64.757
    }, {
      lat: 25.774,
      lng: -80.190
    }]
  }];

  iw = new google.maps.InfoWindow({
    maxWidth: 200
  });

  var cnt_regions = regions.length;

  for (var i = 0; i < cnt_regions; i++) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(regions[i].lat, regions[i].lng),
      map: map,
      title: regions[i].l,
      cat: regions[i].cat,
      visible: true
    });

    marker.addListener('click', function() {
      if (iw) {
        iw.close();
      }
      iw.setContent("<button onclick=\"javascript:f_set_approved_loc('" + this.title + "');\">Search " + this.title + "</button>");
      iw.setPosition(this.position);
      iw.open(map);
    });

    marker.setMap(map);
    a_mks.push(marker);
  }

  if (typeof(google.maps.Polygon.prototype.polygon_check_clockwise) !== 'function') {
    google.maps.Polygon.prototype.polygon_check_clockwise = polygon_check_clockwise;
  }

  function polygon_check_clockwise(path) {
    var self = this;
    var isCounterClockwise = null;

    if (null === path) {
      throw new Error('Path is optional, but cannot be null');
    }

    // default to the first path
    if (arguments.length === 0) {
      path = self.getPath();
    }

    // support for passing an index number to a path
    if (typeof(path) === 'number') {
      path = self.getPaths().getAt(path);
    }

    if (!path instanceof Array && !path instanceof google.maps.MVCArray) {
      throw new Error('Path must be an Array or MVCArray');
    }

    // negative polygon areas have counter-clockwise paths
    isCounterClockwise = (google.maps.geometry.spherical.computeSignedArea(path) < 0);

    return (isCounterClockwise);
  }


}



function get_polygon_boundary(py) {
  if (py.polygon_check_clockwise() === true) {
    alert("clockwise");
  }
  map.fitBounds(py.getBounds());
}

function f_set_approved_loc(region) {
  if (region) {
    var c_polylist = regions.length;

    for (var i = 0; i < c_polylist; i++) {
      if (regions[i].l == region) {
        var ply = new google.maps.Polygon({
          paths: regions[i].poly,
          strokeColor: '#FFCC00',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: '#FFCC00',
          fillOpacity: 0.35
        });

        //map.fitBounds(ply.getBounds());

        get_polygon_boundary(ply);
      }
    }
  }
}
html,
body {
  height: 100%;
  min-height: 100%;
}

html,
body,
div,
p {
  margin: 0;
  padding: 0;
}

body {
  background-color: #eeeeee;
}
<script src="//maps.googleapis.com/maps/api/js?libraries=drawing,visualization&callback=initialize" async defer></script>

<body>
  <div id="map" style="height: 100%; width: 100%;"></div>
</body>

您正在请求库 drawingvisualization(据我所知您没有使用)

<script src="//maps.googleapis.com/maps/api/js?libraries=drawing,visualization&callback=initialize" async defer></script>

但是如果你使用 google.maps.geometry.spherical.computeSignedArea 你应该包括 geometry library

<script src="//maps.googleapis.com/maps/api/js?libraries=geometry,drawing,visualization&callback=initialize" async defer></script>

更改后,我没有遇到任何问题 运行 您的代码。 (我只是更改了函数以实际显示多边形,顺便说一句)

var google, map, iw;
    var a_mks = [];

    // ==========================================

    function initialize() {

      //create map
      map = new google.maps.Map(
        document.getElementById("map"), {
          center: new google.maps.LatLng(25.774, -80.190),
          zoom: 4,
          mapTypeId: google.maps.MapTypeId.TERRAIN,
          zoomControl: true
        });

      // add getbounds to google maps functions
      google.maps.Polygon.prototype.getBounds = function() {
        var b = new google.maps.LatLngBounds();
        var paths = this.getPaths();
        var path;
        for (var i = 0; i < paths.getLength(); i++) {
          path = paths.getAt(i);
          for (var ii = 0; ii < path.getLength(); ii++) {
            b.extend(path.getAt(ii));
          }
        }
        return b;
      }

      regions = [{
        cat: 'Region',
        l: 'Bermuda Triangle',
        lat: 25.774,
        lng: -80.190,
        zoom: 9,
        poly: [{
          lat: 25.774,
          lng: -80.190
        }, {
          lat: 18.466,
          lng: -66.118
        }, {
          lat: 32.321,
          lng: -64.757
        }, {
          lat: 25.774,
          lng: -80.190
        }]
      }];

      iw = new google.maps.InfoWindow({
        maxWidth: 200
      });

      var cnt_regions = regions.length;

      for (var i = 0; i < cnt_regions; i++) {
        var marker = new google.maps.Marker({
          position: new google.maps.LatLng(regions[i].lat, regions[i].lng),
          map: map,
          title: regions[i].l,
          cat: regions[i].cat,
          visible: true
        });

        marker.addListener('click', function() {
          if (iw) {
            iw.close();
          }
          iw.setContent("<button onclick=\"javascript:f_set_approved_loc('" + this.title + "');\">Search " + this.title + "</button>");
          iw.setPosition(this.position);
          iw.open(map);
        });

        marker.setMap(map);
        a_mks.push(marker);
      }

      if (typeof(google.maps.Polygon.prototype.polygon_check_clockwise) !== 'function') {
        google.maps.Polygon.prototype.polygon_check_clockwise = polygon_check_clockwise;
      }

      function polygon_check_clockwise(path) {
        var self = this;
        var isCounterClockwise = null;

        if (null === path) {
          throw new Error('Path is optional, but cannot be null');
        }

        // default to the first path
        if (arguments.length === 0) {
          path = self.getPath();
        }

        // support for passing an index number to a path
        if (typeof(path) === 'number') {
          path = self.getPaths().getAt(path);
        }

        if (!path instanceof Array && !path instanceof google.maps.MVCArray) {
          throw new Error('Path must be an Array or MVCArray');
        }

        // negative polygon areas have counter-clockwise paths
        isCounterClockwise = (google.maps.geometry.spherical.computeSignedArea(path) < 0);

        return (isCounterClockwise);
      }


    }



    function get_polygon_boundary(py) {
      if (py.polygon_check_clockwise() === true) {
        alert("clockwise");
      }
      map.fitBounds(py.getBounds());
    }

    function f_set_approved_loc(region) {
      if (region) {
        var c_polylist = regions.length;

        for (var i = 0; i < c_polylist; i++) {
          if (regions[i].l == region) {
            var ply = new google.maps.Polygon({
              map: map,
              paths: regions[i].poly,
              strokeColor: '#FFCC00',
              strokeOpacity: 0.8,
              strokeWeight: 2,
              fillColor: '#FFCC00',
              fillOpacity: 0.35
            });

            //map.fitBounds(ply.getBounds());

            get_polygon_boundary(ply);
          }
        }
      }
    }
html,
    body {
      height: 100%;
      min-height: 100%;
    }
    
    html,
    body,
    div,
    p {
      margin: 0;
      padding: 0;
    }
    
    body {
      background-color: #eeeeee;
    }
<script src="https://maps.googleapis.com/maps/api/js?&libraries=geometry&callback=initialize" async defer></script>

  <div id="map" style="height: 100%; width: 100%;"></div>