JSFiddle - React, Tailwind, and code Playground
by Lawrence Ross
HTML
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<script src="https://cdn.rawgit.com/bjornharrtell/jsts/gh-pages/1.0.2/jsts.min.js"></script>
<div id="map_canvas"></div>
CSS
html, body, #map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
JavaScript
var googleMaps2JSTS = function(boundaries) {
var coordinates = [];
for (var i = 0; i < boundaries.getLength(); i++) {
coordinates.push(new jsts.geom.Coordinate(
boundaries.getAt(i).lat(), boundaries.getAt(i).lng()));
}
return coordinates;
};
var jsts2googleMaps = function(geometry) {
var coordArray = geometry.getCoordinates();
GMcoords = [];
for (var i = 0; i < coordArray.length; i++) {
GMcoords.push(new google.maps.LatLng(coordArray[i].x, coordArray[i].y));
}
return GMcoords;
}
function initialize() {
var 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
});
var bounds = new google.maps.LatLngBounds();
var poly1 = new google.maps.Polygon({
// map: map,
paths: [polyPath1]
});
for (var i=0;i<polyPath1.length;i++) {
bounds.extend(new google.maps.LatLng(polyPath1[i].lat,polyPath1[i].lng));
}
var poly2 = new google.maps.Polygon({
// map: map,
paths: [polyPath2]
});
for (var i=0;i<polyPath2.length;i++) {
bounds.extend(new google.maps.LatLng(polyPath2[i].lat,polyPath2[i].lng));
}
map.fitBounds(bounds);
var geometryFactory = new jsts.geom.GeometryFactory();
var JSTSpoly1 = geometryFactory.createPolygon(geometryFactory.createLinearRing(googleMaps2JSTS(poly1.getPath())));
JSTSpoly1.normalize();
var JSTSpoly2 = geometryFactory.createPolygon(geometryFactory.createLinearRing(googleMaps2JSTS(poly2.getPath())));
JSTSpoly2.normalize();
var JSTSpolyUnion = JSTSpoly1.union(JSTSpoly2);
var outputPath = jsts2googleMaps(JSTSpolyUnion);
var unionPoly = new google.maps.Polygon({
map: map,
paths: outputPath,
strokeColor: '#0000FF',
strokeOpacity: 0.3,
strokeWeight: 2,
fillColor: '#0000FF',
fillOpacity: 0.8
});
}
google.maps.event.addDomListener(window, "load",...