JSFiddle - React, Tailwind, and code Playground
by Dung Nguyen
HTML
<!DOCTYPE html>
<html>
<head>
<title>Data Layer: Polygon</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly&channel=2"
async
></script>
</body>
</html>
CSS
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
// This example uses the Google Maps JavaScript API's Data layer
// to create a rectangular polygon with 2 holes in it.
const places = [
{
center: { "lat": 1.3512492664554796, "lng": 103.85072488875811 },
radius: 2000
},
{
center: { "lat": 1.3225896205754812, "lng": 103.86600275130694 },
radius: 2000
},
{
center:{ "lat": 1.3136655910729036, "lng": 103.88866205306475 },
radius: 2000
},
{
center: { "lat": 1.305427997082587, "lng": 103.83613367171709 },
radius: 2000
}
];
let map;
const mapDefault = {
center: places[0].center,
zoom: 10,
minZoom: 1,
maxZoom: 19,
clickableIcons: false
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), mapDefault);
const bounds = new google.maps.LatLngBounds();
let pathsCircle = [];
places.forEach(place => {
bounds.extend(place.center);
pathsCircle.push(drawCircle(place.center, place.radius, 1));
});
map.fitBounds(bounds);
const worldCoords = [
new google.maps.LatLng(-85.1054596961173, -180),
new google.maps.LatLng(85.1054596961173, -180),
new google.maps.LatLng(85.1054596961173, 180),
new google.maps.LatLng(-85.1054596961173, 180),
new google.maps.LatLng(-85.1054596961173, 0)
];
new google.maps.Polygon({
paths: [worldCoords, ...pathsCircle],
strokeColor: '#fff',
strokeOpacity: 0,
strokeWeight: 0,
fillColor: '#000',
fillOpacity: 0.3,
map,
});
}
function drawCircle(point, radius, dir) {
let d2r = Math.PI / 180; // degrees to radians
let r2d = 180 / Math.PI; // radians to degrees
let earthsradius = 6378137; // 6378137 is the radius of the earth in metters
let points = 128; // number of point to draw Circle
// find the raidus in lat/lon
let rlat = (radius / earthsradius) * r2d;
let rlng = rlat / Math.cos(point.lat * d2r);
let extp = [];
let start, end;
if (dir == 1) { // one extra here makes sure we connect the
start...