-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmapkit.js
More file actions
337 lines (283 loc) · 11.1 KB
/
mapkit.js
File metadata and controls
337 lines (283 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/**
* Яндекс Карты - Базовый API
* Основные функции для работы с картами
*/
class YandexMapKit {
constructor() {
this.map = null;
this.objects = [];
this.markers = [];
this.polygons = [];
this.polylines = [];
this.isInitialized = false;
this.init();
}
/**
* Инициализация карты
*/
init() {
// Ждем загрузки API Яндекс Карт
if (typeof ymaps !== 'undefined') {
this.createMap();
} else {
// Если API еще не загружен, ждем
window.addEventListener('load', () => {
if (typeof ymaps !== 'undefined') {
this.createMap();
} else {
console.error('API Яндекс Карт не загружен');
}
});
}
}
/**
* Создание карты
*/
createMap() {
try {
// Создаем карту с центром в Москве
this.map = new ymaps.Map('map', {
center: [55.7558, 37.6176], // Москва
zoom: 10,
controls: ['zoomControl', 'fullscreenControl', 'geolocationControl']
});
this.isInitialized = true;
this.setupEventListeners();
this.updateInfo();
console.log('Карта успешно инициализирована');
} catch (error) {
console.error('Ошибка при создании карты:', error);
}
}
/**
* Настройка обработчиков событий
*/
setupEventListeners() {
// Обработчики для кнопок
document.getElementById('addMarker').addEventListener('click', () => this.addRandomMarker());
document.getElementById('addPolygon').addEventListener('click', () => this.addRandomPolygon());
document.getElementById('addPolyline').addEventListener('click', () => this.addRandomPolyline());
document.getElementById('clearAll').addEventListener('click', () => this.clearAll());
document.getElementById('getCenter').addEventListener('click', () => this.getCenter());
document.getElementById('setZoom').addEventListener('click', () => this.setRandomZoom());
// Обработчики событий карты
this.map.events.add('boundschange', () => this.updateInfo());
this.map.events.add('zoomchange', () => this.updateInfo());
}
/**
* Добавление случайного маркера
*/
addRandomMarker() {
if (!this.isInitialized) return;
const center = this.map.getCenter();
const lat = center[0] + (Math.random() - 0.5) * 0.1;
const lon = center[1] + (Math.random() - 0.5) * 0.1;
const marker = new ymaps.Placemark([lat, lon], {
balloonContent: `Маркер ${this.markers.length + 1}`
}, {
preset: 'islands#blueDotIcon'
});
this.map.geoObjects.add(marker);
this.markers.push(marker);
this.objects.push(marker);
this.updateInfo();
console.log(`Добавлен маркер: [${lat.toFixed(6)}, ${lon.toFixed(6)}]`);
}
/**
* Добавление случайного полигона
*/
addRandomPolygon() {
if (!this.isInitialized) return;
const center = this.map.getCenter();
const radius = 0.01;
const points = [];
// Создаем многоугольник с случайными точками
for (let i = 0; i < 5; i++) {
const angle = (i / 5) * 2 * Math.PI;
const lat = center[0] + radius * Math.cos(angle) + (Math.random() - 0.5) * 0.005;
const lon = center[1] + radius * Math.sin(angle) + (Math.random() - 0.5) * 0.005;
points.push([lat, lon]);
}
const polygon = new ymaps.Polygon([points], {
balloonContent: `Полигон ${this.polygons.length + 1}`
}, {
fillColor: this.getRandomColor(),
strokeColor: '#000000',
strokeWidth: 2,
fillOpacity: 0.6
});
this.map.geoObjects.add(polygon);
this.polygons.push(polygon);
this.objects.push(polygon);
this.updateInfo();
console.log(`Добавлен полигон с ${points.length} точками`);
}
/**
* Добавление случайной линии
*/
addRandomPolyline() {
if (!this.isInitialized) return;
const center = this.map.getCenter();
const points = [];
// Создаем линию с случайными точками
for (let i = 0; i < 3; i++) {
const lat = center[0] + (Math.random() - 0.5) * 0.1;
const lon = center[1] + (Math.random() - 0.5) * 0.1;
points.push([lat, lon]);
}
const polyline = new ymaps.Polyline([points], {
balloonContent: `Линия ${this.polylines.length + 1}`
}, {
strokeColor: this.getRandomColor(),
strokeWidth: 3
});
this.map.geoObjects.add(polyline);
this.polylines.push(polyline);
this.objects.push(polyline);
this.updateInfo();
console.log(`Добавлена линия с ${points.length} точками`);
}
/**
* Очистка всех объектов
*/
clearAll() {
if (!this.isInitialized) return;
this.map.geoObjects.removeAll();
this.markers = [];
this.polygons = [];
this.polylines = [];
this.objects = [];
this.updateInfo();
console.log('Все объекты удалены');
}
/**
* Получение центра карты
*/
getCenter() {
if (!this.isInitialized) return;
const center = this.map.getCenter();
const coords = `[${center[0].toFixed(6)}, ${center[1].toFixed(6)}]`;
// Показываем информацию в alert (можно заменить на более красивое уведомление)
alert(`Центр карты: ${coords}`);
console.log('Центр карты:', coords);
return center;
}
/**
* Установка случайного зума
*/
setRandomZoom() {
if (!this.isInitialized) return;
const newZoom = Math.floor(Math.random() * 15) + 5; // Зум от 5 до 19
this.map.setZoom(newZoom);
console.log(`Установлен зум: ${newZoom}`);
}
/**
* Обновление информации о карте
*/
updateInfo() {
if (!this.isInitialized) return;
const center = this.map.getCenter();
const zoom = this.map.getZoom();
document.getElementById('centerCoords').textContent =
`[${center[0].toFixed(6)}, ${center[1].toFixed(6)}]`;
document.getElementById('currentZoom').textContent = zoom;
document.getElementById('objectCount').textContent = this.objects.length;
}
/**
* Генерация случайного цвета
*/
getRandomColor() {
const colors = [
'#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
'#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9'
];
return colors[Math.floor(Math.random() * colors.length)];
}
/**
* Поиск по адресу
*/
async searchByAddress(address) {
if (!this.isInitialized) return null;
try {
const geocoder = ymaps.geocode(address);
const result = await geocoder;
if (result.geoObjects.getLength() > 0) {
const coords = result.geoObjects.get(0).geometry.getCoordinates();
this.map.setCenter(coords, 15);
console.log(`Найден адрес: ${address} -> [${coords[0]}, ${coords[1]}]`);
return coords;
} else {
console.log(`Адрес не найден: ${address}`);
return null;
}
} catch (error) {
console.error('Ошибка при поиске адреса:', error);
return null;
}
}
/**
* Измерение расстояния между двумя точками
*/
calculateDistance(point1, point2) {
if (!this.isInitialized) return 0;
try {
const distance = ymaps.coordSystem.geo.getDistance(point1, point2);
return Math.round(distance);
} catch (error) {
console.error('Ошибка при расчете расстояния:', error);
return 0;
}
}
/**
* Получение информации об объекте по клику
*/
enableClickInfo() {
if (!this.isInitialized) return;
this.map.events.add('click', (e) => {
const coords = e.get('coords');
console.log(`Клик по координатам: [${coords[0].toFixed(6)}, ${coords[1].toFixed(6)}]`);
// Можно добавить маркер по клику
const marker = new ymaps.Placemark(coords, {
balloonContent: `Клик: [${coords[0].toFixed(6)}, ${coords[1].toFixed(6)}]`
});
this.map.geoObjects.add(marker);
this.markers.push(marker);
this.objects.push(marker);
this.updateInfo();
});
}
/**
* Экспорт карты в изображение
*/
exportToImage() {
if (!this.isInitialized) return;
try {
// Создаем скриншот карты
this.map.getBounds().then(bounds => {
console.log('Границы карты:', bounds);
// Здесь можно добавить логику экспорта
});
} catch (error) {
console.error('Ошибка при экспорте:', error);
}
}
}
// Инициализация приложения
document.addEventListener('DOMContentLoaded', () => {
console.log('Инициализация Яндекс Карт...');
// Создаем экземпляр API
window.mapKit = new YandexMapKit();
// Включаем получение информации по клику
setTimeout(() => {
if (window.mapKit.isInitialized) {
window.mapKit.enableClickInfo();
}
}, 1000);
});
// Глобальные функции для удобства использования
window.addMarker = () => window.mapKit?.addRandomMarker();
window.addPolygon = () => window.mapKit?.addRandomPolygon();
window.addPolyline = () => window.mapKit?.addRandomPolyline();
window.clearAll = () => window.mapKit?.clearAll();
window.getCenter = () => window.mapKit?.getCenter();
window.setZoom = () => window.mapKit?.setRandomZoom();