Search code examples
javascriptgoogle-mapsgoogle-maps-api-3geolocation

Get polygons from google map


I have a kml file with a bunch of polygons. I manged to create a google map and load this kml following the documentation.

(function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 11,
          center: {lat: 41.876, lng: -87.624}
        });

        var ctaLayer = new google.maps.KmlLayer({
          url: 'http://myurl.dev/polygons.kml',
          map: map
        });

})();     

Now, I want to retrieve all the polygons from this kml in order the ask if a point (lat,long) is within some of them.

google.maps.geometry.poly.containsLocation(point, OnePolygonFromMyMap);

The problem, is that I did not find any documentation to get all the shapes the map contains. Is this possible?


Solution

  • You can't access the polygons on the map when they are placed there using KmlLayer, google.maps.KmlLayer is uses tile based rendering, you can't (at least at present) access the coordinates of the polygons except on a click.

    Note however that rendering the polygons as native google.maps.Polygon objects (as the third party libraries do) could have a performance penalty, particularly if your KML is complex.

    You could use a third party KML parser like geoxml3 or geoxml-v3 to render the polygons as native google.maps.Polygon objects, and get their center. This will have performance issues with complex KML.

    example using geoxml3