Search code examples
javascriptgoogle-mapsgoogle-maps-api-3latitude-longitude

Filling Google Maps polygon from array of LatLng points


I have an array of coordinates in LatLng format. I would like to construct a polygon using those coordinates. I know I can hardcode a polygon with individual coordinates like this:

var triangleCoords = [
    {lat: A, lng: A},
    {lat: B, lng: B},
    {lat: C, lng: C}]

Is it possible to place the LatLng data points from my array into triangleCoords and create the polygon that way?


Solution

  • Correct me if I had misunderstood your question.

    Q: Is it possible to place the LatLng data points from my array into triangleCoords and create the polygon that way?

    A:

    Short answer: No. Unfortunately there is no smartness in the google.maps.Polygon code which would magically try to figure out the lat and lng coordinates of the specified google.maps.LatLng objects for you.

    You will need to use the lat() and lng() APIs to return the raw coordinate values from the google.maps.LatLng object and plug that into your array. No shortcut.

    Example:

    var map = new google.maps.Map(document.getElementById("map"),
    {
        zoom: 4,
        center: new google.maps.LatLng(22.7964, 79.8456),
        mapTypeId: google.maps.MapTypeId.HYBRID
    });
    
    var coordinateA = new google.maps.LatLng(18.979026,72.949219);
    var coordinateB = new google.maps.LatLng(28.613459,77.255859);
    var coordinateC = new google.maps.LatLng(22.512557,88.417969);
    var coordinateD = new google.maps.LatLng(12.940322,77.607422);
    
    var coords =
        [
            {lat: coordinateA.lat(), lng: coordinateA.lng() },
            {lat: coordinateB.lat(), lng: coordinateB.lng() },
            {lat: coordinateC.lat(), lng: coordinateC.lng() },
            {lat: coordinateD.lat(), lng: coordinateD.lng() }
        ];
    
    metros = new google.maps.Polygon(
        {
            paths: coords,
            strokeColor: "#0000FF",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#0000FF",
            fillOpacity: 0.26
        });
    

    See here for a working JSFiddle example. http://jsfiddle.net/SamuelToh/3srggbmu/