-1

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!

Community
  • 1
  • 1
  • 1
    What you're seeing is a LatLng object. Why not just use `myPolygon.my_getBounds().getCenter().lat()` and `myPolygon.my_getBounds().getCenter().lng()`, or am I misunderstanding the request? – duncan Mar 31 '16 at 20:30
  • @duncan WOW, thank you! This was so easy! I spent 4 hours researching this. Yes this solves my problem completely. I'm new to this, so I did not know how to deal with this LatLng object. Thank you very much again! – PunainenAurinko Mar 31 '16 at 21:46

1 Answers1

4

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();
duncan
  • 31,401
  • 13
  • 78
  • 99