Skip to content

Instantly share code, notes, and snippets.

@dshster
Created October 7, 2017 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dshster/29a3678bb06e10ab93da7b1b0b67df77 to your computer and use it in GitHub Desktop.
Save dshster/29a3678bb06e10ab93da7b1b0b67df77 to your computer and use it in GitHub Desktop.
Yandex Maps random polygones
const margin = 200;
const theta = 0.2;
function getRandomCoords({ width, height }) {
return {
top: Math.random() * (width - margin) + margin / 2,
left: Math.random() * (height - margin) + margin / 2,
};
}
function getRandomShape() {
const width = map.clientWidth;
const height = map.clientHeight;
const center = getRandomCoords({ width, height });
const corners = [...new Array(10).keys()];
return corners
.map(point => Math.random() * 360 * Math.PI / 180)
.sort((a, b) => a - b)
.reduce((list, point) => {
const prev = list.length && list[list.length - 1];
if (point - prev > theta) {
list.push(point);
}
return list;
}, [])
.map(point => {
const diameter = Math.random() * 50 + 25;
const x = diameter * Math.cos(point);
const y = diameter * Math.sin(point);
return { top: center.top + y, left: center.left + x };
});
}
ymaps.ready(() => {
const map = document.getElementById('map');
const seed = document.getElementById('seed');
const list = document.getElementById('list');
const yMap = new ymaps.Map('map', {
center: [55.751574, 37.573856],
zoom: 9
}, {
searchControlProvider: 'yandex#search'
});
const projection = yMap.options.get('projection');
seed.addEventListener('click', () => {
const coords = getRandomShape();
const shape = coords.map(point => projection.fromGlobalPixels(
yMap.converter.pageToGlobal([point.left, point.top]), yMap.getZoom()
));
const myPolygon = new ymaps.Polygon([
shape
], {
hintContent: "Многоугольник"
}, {
fillColor: '#00FF0088',
strokeWidth: 5
});
yMap.geoObjects.add(myPolygon);
});
list.addEventListener('click', () => {
const list = [];
yMap.geoObjects.each(geo => {
list.push(geo.geometry.getCoordinates()[0])
});
console.log(list);
});
});
<!DOCTYPE html>
<html>
<head>
<title>Примеры. Метка</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="http://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
<script src="application.js" type="text/javascript"></script>
<style>
#map {
width: 800px;
height: 600px;
padding: 0;
margin: 0;
border: 1px solid #faf;
position: relative;
}
.point {
position: absolute;
width: 10px;
height: 10px;
margin-top: -5px;
margin-left: -5px;
}
</style>
</head>
<body>
<div id="map"></div>
<button id="seed">seed</button>
<button id="list">list</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment