简体   繁体   中英

Center of Polygon Google Maps JavaScript API v3

I looked through this thread: How to get the center of a polygon in google maps v3? , and Matthew Scharley's answer currently marked as correct does not do it for me. I am downloading corner coordinates for 50-100 polygons dynamically from the server in an array of lat/long objects, and I need a dynamic not manual solution for determining polygon centers. The answer from the same thread by furiozo comes close to fulfilling my needs, as it calculates the average center of the polygon, but the results that I see in my console.log from his function:

google.maps.Polygon.prototype.my_getBounds=function(){
    var bounds = new google.maps.LatLngBounds()
    this.getPath().forEach(function(element,index){bounds.extend(element)})
    return bounds
}

console.log(myPolygon.my_getBounds().getCenter());

are not something that I can readily use in my program.

What I get in the console is this:

_.M {}
   lat: function ()
      arguments: (...)
      caller: (...)
      length: 0
      name: ""
      prototype: Object
      __proto__: function ()
      <function scope>
        Closure
          a: 45.256705626
          b: -75.91270512
        Closure 
        Global: Window
   lng: function() -- contains same sub-levels as lat: function() --
   __proto__: Object

What I really need right now is how to get to the a & b lat/lng values that sit under the first Closure level in in lat: function() in the object I'm getting in my console. (I have checked manually by substituting these results in code, they represent the correct center for the first of my polygons). Any help with how to get to them will be greatly appreciated.

Or, if anybody knows of any up-to-date solution for how to get average polygon center coordinate values dynamically so that the end result will be in the format of (lat, lng), this may save my day.

Thank you very much!

What you're seeing is a LatLng object.

What you can do is simply call the lat() and lng() functions on it:

var lat = myPolygon.my_getBounds().getCenter().lat();
var lng = myPolygon.my_getBounds().getCenter().lng();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM