How to use a polygon string in google maps api

2.9k views Asked by At

I have the following polygon string:

POLYGON ((5.031728766 52.016855117, 5.039437914 52.018712029, 5.038732065 52.01933205, 5.03880625 52.019536002, 5.036666299 52.021123062, 5.037225302 52.021436208, 5.036494826 52.021980534, 5.040069034 52.024180983, 5.041131857 52.023541011, 5.041485972 52.023745389, 5.042328698 52.023235595, 5.043167194 52.022781293, 5.043379189 52.022938683, 5.04366399 52.022788333, 5.044615961 52.023393034, 5.046878469 52.022023355, 5.047609948 52.02119413, 5.048777737 52.022018526, 5.049465821 52.022060318, 5.05135083 52.021274278999996, 5.053039915 52.020873436, 5.052288001 52.019935439, 5.052174884 52.019294199, 5.053026298 52.019318482, 5.053120663 52.018982405, 5.05237284 52.018935127, 5.051442801 52.019120203, 5.046607457 52.016128313, 5.046220739 52.015628312, 5.04412241 52.015134981, 5.043853082 52.015544473, 5.043410675 52.015932024, 5.042704158 52.016254485, 5.042235947 52.016357569, 5.040118936 52.0166409, 5.039579367 52.015163505, 5.034087326 52.015907152, 5.03224395 52.016039016, 5.031728766 52.016855117), (5.043324081 52.017406693, 5.046676295 52.019354241, 5.048003676 52.020235065, 5.046772806 52.021010583, 5.045897693 52.02180469, 5.043619067 52.020981305, 5.042189351 52.020258164, 5.039736347 52.018909018, 5.041350353 52.018037167, 5.042763839 52.01739758, 5.042763839 52.01739758, 5.043324081 52.017406693))

I would like to use it to plot a simple polygon using the Google Maps API, e.g.:

var triangleCoords = [
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.75737),
    new google.maps.LatLng(25.774252, -80.190262)
  ];

How can I:

  • either iterate over the text and grab the coordinates
  • use an alternative more efficient way with google.maps.LatLng(POLYGONTEXTSTRING)
2

There are 2 answers

2
geocodezip On BEST ANSWER

Using modified code from this related question: Polygon array does not work in Google map API. Your string is formatted slightly differently, don't know if that was on purpose.

proof of concept fiddle

screenshot of map

code snippet:

var map;
var bounds = new google.maps.LatLngBounds();

// your POLYGON
var polygonStr = "POLYGON ((5.031728766 52.016855117, 5.039437914 52.018712029, 5.038732065 52.01933205, 5.03880625 52.019536002, 5.036666299 52.021123062, 5.037225302 52.021436208, 5.036494826 52.021980534, 5.040069034 52.024180983, 5.041131857 52.023541011, 5.041485972 52.023745389, 5.042328698 52.023235595, 5.043167194 52.022781293, 5.043379189 52.022938683, 5.04366399 52.022788333, 5.044615961 52.023393034, 5.046878469 52.022023355, 5.047609948 52.02119413, 5.048777737 52.022018526, 5.049465821 52.022060318, 5.05135083 52.021274278999996, 5.053039915 52.020873436, 5.052288001 52.019935439, 5.052174884 52.019294199, 5.053026298 52.019318482, 5.053120663 52.018982405, 5.05237284 52.018935127, 5.051442801 52.019120203, 5.046607457 52.016128313, 5.046220739 52.015628312, 5.04412241 52.015134981, 5.043853082 52.015544473, 5.043410675 52.015932024, 5.042704158 52.016254485, 5.042235947 52.016357569, 5.040118936 52.0166409, 5.039579367 52.015163505, 5.034087326 52.015907152, 5.03224395 52.016039016, 5.031728766 52.016855117), (5.043324081 52.017406693, 5.046676295 52.019354241, 5.048003676 52.020235065, 5.046772806 52.021010583, 5.045897693 52.02180469, 5.043619067 52.020981305, 5.042189351 52.020258164, 5.039736347 52.018909018, 5.041350353 52.018037167, 5.042763839 52.01739758, 5.042763839 52.01739758, 5.043324081 52.017406693))";


function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  drawPoly(polygonStr);
  map.fitBounds(bounds);

}

function drawPoly(multipolygonWKT) {
  var polylines = [];
  var toReturn = [];
  multipolygonWKT = multipolygonWKT.replace("POLYGON ", "");
  var formattedValues = multipolygonWKT.replace("))", "");
  formattedValues = formattedValues.replace("((", "");

  var linesCoords = formattedValues.split("), (");

  for (i = 0; i < linesCoords.length; i++) {
    polylines[i] = [];
    var singleLine = linesCoords[i].split(", ");

    for (j = 0; j < singleLine.length; j++) {
      var coordinates = singleLine[j].split(" ");
      var latlng = new google.maps.LatLng(parseFloat(coordinates[1]), parseFloat(coordinates[0]));
      bounds.extend(latlng);

      polylines[i].push(latlng);

    }
  }

  toReturn.push(
    new google.maps.Polygon({
      map: map,
      paths: polylines,
      strokeColor: 'red',
      strokeOpacity: 1,
      strokeWeight: 2,
      zIndex: 1
    }));
  return toReturn;
}

google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

<div id="map_canvas"border: 2px solid #3872ac;"></div>

1
Vadim Gremyachev On

Since paths parameter of google.maps.Polygon object expects the array of google.maps.LatLng to be specified, the following example demonstrates how to parse input string:

function parsePolygonPaths(svalue)
{
    var result = [];
    var r = /\(([^)]+)\)/g;
    svalue = svalue.slice(9, -1);
    while (matches = r.exec(svalue)) {
       var vals = matches[1].split(',');
       var coords = vals.map(function(val){
          var ll = val.trim().split(' ');
          return new google.maps.LatLng(ll[0], ll[1]);  
       });
       result.push(coords);
    }
    return result;
}

It is assumed that input string has the following format:

POLYGON ((lat11 lng11,..lat1n,lng1n),(lat21 lng21,..lat2n,lng2n),..(latn1 lngn1,..latnn,lngnn))

Returned value:

[
  [google.maps.LatLng(lat11,lng11),..google.maps.LatLng(lat1n,lng1n)]
  [google.maps.LatLng(lat21,lng21),..google.maps.LatLng(lat2n,lng2n)]
 ..
  [google.maps.LatLng(latn1,lngn1),..google.maps.LatLng(latnn,lngnn)]
]

Example

var polygonString = 'POLYGON ((5.031728766 52.016855117, 5.039437914 52.018712029, 5.038732065 52.01933205, 5.03880625 52.019536002, 5.036666299 52.021123062, 5.037225302 52.021436208, 5.036494826 52.021980534, 5.040069034 52.024180983, 5.041131857 52.023541011, 5.041485972 52.023745389, 5.042328698 52.023235595, 5.043167194 52.022781293, 5.043379189 52.022938683, 5.04366399 52.022788333, 5.044615961 52.023393034, 5.046878469 52.022023355, 5.047609948 52.02119413, 5.048777737 52.022018526, 5.049465821 52.022060318, 5.05135083 52.021274278999996, 5.053039915 52.020873436, 5.052288001 52.019935439, 5.052174884 52.019294199, 5.053026298 52.019318482, 5.053120663 52.018982405, 5.05237284 52.018935127, 5.051442801 52.019120203, 5.046607457 52.016128313, 5.046220739 52.015628312, 5.04412241 52.015134981, 5.043853082 52.015544473, 5.043410675 52.015932024, 5.042704158 52.016254485, 5.042235947 52.016357569, 5.040118936 52.0166409, 5.039579367 52.015163505, 5.034087326 52.015907152, 5.03224395 52.016039016, 5.031728766 52.016855117), (5.043324081 52.017406693, 5.046676295 52.019354241, 5.048003676 52.020235065, 5.046772806 52.021010583, 5.045897693 52.02180469, 5.043619067 52.020981305, 5.042189351 52.020258164, 5.039736347 52.018909018, 5.041350353 52.018037167, 5.042763839 52.01739758, 5.042763839 52.01739758, 5.043324081 52.017406693))';

function initialize() {
    var mapOptions = {
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };


    var map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);

    var result = parsePolygonPaths(polygonString);     
   
    var bounds = new google.maps.LatLngBounds();
    // Construct the polygon.
    result.forEach(function(coords){
           
          coords.forEach(function(loc){
              bounds.extend(loc); 
          });

          var poly = new google.maps.Polygon({
                          paths: coords,
                          strokeColor: '#FF0000',
                          strokeOpacity: 0.8,
                          strokeWeight: 2,
                          fillColor: '#FF0000',
                          fillOpacity: 0.35
                    });
          poly.setMap(map);               
    });

    map.fitBounds(bounds);
    map.panToBounds(bounds);   
   
}

google.maps.event.addDomListener(window, 'load', initialize);



function parsePolygonPaths(svalue)
{
    var result = [];
    var r = /\(([^)]+)\)/g;
    svalue= svalue.slice(9, -1);
    while (matches = r.exec(svalue)) {
       var vals = matches[1].split(',');
       var coords = vals.map(function(val){
          var ll = val.trim().split(' ');
          return new google.maps.LatLng(ll[1], ll[0]);  
       });
       result.push(coords);
    }
    return result;
}
  html, body, #map-canvas {
            height: 100%;
            margin: 0px;
            padding: 0px;
  }
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<div id="map-canvas"></div>