/* * Let's GO! */ var myMap; var categories = Array(); var points = Array(); var pointsSources = Array(); var markers; // Используется для кластеризации var search; var route = false; var addPointInProcess = false; var layer; var layers = Array(); var defaultZoom = 13; var rightCoords = []; categories.im = L.icon({ iconUrl: '/ico/man.png', iconSize: [32, 37], iconAnchor: [16, 37], popupAnchor: [0, 1] }); categories.lock = L.icon({ iconUrl: '/ico/lock.png', iconSize: [32, 37], iconAnchor: [16, 37], popupAnchor: [0, 1] }); categories.simplepoint = L.icon({ iconUrl: '/ico/simplepoint.png', iconSize: [13, 13], iconAnchor: [7, 7], popupAnchor: [7, 7] }); // ----------------------------------------------------------------------------- /** * Инициализируем яндекс-карты и узнаём расположение пользователя. */ ymaps.ready(function () { lat = ymaps.geolocation.latitude; lng = ymaps.geolocation.longitude; if (pointLat == pointLng) { init(lat, lng); } else { init(pointLat, pointLng); } points.im = L.marker([lat, lng], {icon: categories.im, title: 'Вы здесь'}); points.im.addTo(myMap); points.im.bindPopup('

Похоже, что вы здесь!

Ваше местоположение - это точка, которую можно добавить в маршрут. При первоначальной загрузке страницы определение координат происходит очень неточно, по вашему адресу в сети интеренет. При желании координаты можно уточнить, нажав соответствующую пиктограмму справа [
].

'); suggestInit('#addressField'); }); /** * Инициализируем переменные и подгружаем данные. * @returns true */ function init(lat, lng) { myMap = L.map('map', {zoomControl: false}).setView([lat, lng], defaultZoom); markers = new L.MarkerClusterGroup({showCoverageOnHover: false, maxClusterRadius: 45}); layers['quest'] = L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox', maxZoom: 18}); layers['osm'] = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery ©', maxZoom: 18}); layers['topo'] = L.tileLayer('http://topo.wikipoints.ru/?z={z}&x={x}&y={y}', {attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Маршруты.ру', maxZoom: 15}); layers['google'] = new L.Google('HYBRID'); layers['yandexMap'] = new L.Yandex(); layers['yandex'] = new L.Yandex('hybrid'); setLayer($.cookie('mapLayer') ? $.cookie('mapLayer') : 'quest'); initCategories(); // getPoints внутри myMap.on('click', function (e) { if (!myMap._popup) { if (status == statusHunting) { $('#addPointId').remove(); $('#addPointForm input:text').val(''); $('#addPointForm textarea').val(''); $("#addPointCategoryId option").attr('selected', null); $('#addPointLat').val(e.latlng.lat); $('#addPointLng').val(e.latlng.lng); $('#myModalLabel').text('Добавление новой точки'); $('#addPointModal').modal('show'); } else if (status == statusReHunting) { resetStatus(); $('#addPointLat').val(e.latlng.lat); $('#addPointLng').val(e.latlng.lng); $('#myModalLabel').text('Редактирование точки'); $('#addPointModal').modal('show'); } } else { closePopup(); } }); $("#wayPoints").sortable(); $("#wayPoints").disableSelection(); $("#imgsContainer").sortable(); myMap.on('moveend', function (e) { if (!myMap._popup && $('#boxRoute').css('display') == 'none' && status != statusMovingInHistory) { document.title = pointsCount + ' или даже больше поводов не сидеть дома'; history.pushState({lat: myMap.getCenter().lat, lng: myMap.getCenter().lng, zoom: myMap.getZoom()}, document.title, "/?lat=" + myMap.getCenter().lat + "&lng=" + myMap.getCenter().lng + "&zoom=" + myMap.getZoom()); } if (status == statusMovingInHistory) { resetStatus(); } }); $('.filterSelector').bind('change', function () { filter() }); // Добавление произвольной точки в маршрут по правому клику myMap.on('contextmenu', function (e) { if (status == statusReady) { rightCoords = [e.latlng.lat, e.latlng.lng]; popupContent = ''; popup = L.popup(); popup.setContent(popupContent); popup.setLatLng(e.latlng); popup.openOn(myMap); } }); return true; } /** * Создаёт точку для карты - Placemark. * @param {Array} data * @returns {Array} */ function constructPoint(data) { id = data['id']; icon = categories[data['categoryId']]; if (data['moderate'] != 'show') { icon = categories.lock; data['name'] = 'На модерации: ' + data['name']; } points[id] = L.marker( [data['lat'], data['lng']], {icon: icon, title: data['name'], id: id, categoryId: data['categoryId']} ).on('click', function (e) { if (!(id in pointsSources)) { showInfo(e.target.options.id, true); } else { history.pushState({pointId: id}, document.title, "/?point=" + e.target.options.id); document.title = e.target.options.title; } }); return points[id]; } /** * Загружает точки с сервера. * @returns {Boolean} */ function initPoints() { $.ajax({ url: "/json/points/", success: function (data) { for (var k in data) { markers.addLayer(constructPoint(data[k])); } myMap.addLayer(markers); if (getURLParameter('point') != 'null') { if (getURLParameter('point') == 'random') { showRandomPoint(); } else { showInfo(getURLParameter('point')); } } else if (getURLParameter('route') != 'null') { loadRouteJSON(getURLParameter('route')); buildRoute(true); } else if ((getURLParameter('lat') != 'null') && (getURLParameter('lng') != 'null') && (getURLParameter('zoom') != 'null')) { myMap.setView([getURLParameter('lat'), getURLParameter('lng')], getURLParameter('zoom')); } } }); return true; } /** * Показывает баллун для точки. Если данных для точки нет, то подгружает их с сервера. * @param {type} id * @returns {Boolean} */ function showInfo(id, mapClick) { if (!(id in points)) { return false; } mapClick = Boolean(mapClick !== undefined && mapClick === true); // true если это клик по маркеру на карте marker = points[id]; if (!(id in pointsSources)) { marker.bindPopup("

" + marker.options['title'] + "

Загрузка...").openPopup(); $.ajax({ url: "/json/point/id/" + id, success: function (data) { pointsSources[id] = data; drawInfoPopup(id, true) } }); } else { drawInfoPopup(id, !mapClick); } } function drawInfoPopup(id, showPopup) { data = pointsSources[id]; if (typeof (data.images) == 'object') { photos = '
'; if (data.images.length > 1) photos += '
+' + (data.photosCount - 1) + '
'; photos += ''; photos += '
'; } else { photos = ''; } onModerate = ''; if (data.moderate != 'show') { onModerate = 'На модерации: '; } description = '
' + '

' + onModerate + data.name + '

' + photos; description += data.descriptionHtml; description += '
'; description += '
'; description += ' Подробнее'; description += ''; description += ''; description += ''; if (isAdmin == '1') { description += ''; if (getURLParameter('edit') == 'true') { editPoint(id); } } description += '
'; maxWidth = $(window).width() < 500 ? $(window).width() : 500; maxHeight = $(window).height() < 300 ? $(window).height() : 300; marker.options.description = description; marker.bindPopup(marker.options.description, {maxWidth: maxWidth, minWidth: 400, maxHeight: maxHeight}); markers.zoomToShowLayer(marker, function () { bounds = myMap.getBounds(); diff = (bounds._northEast.lat - bounds._southWest.lat) / 4; myMap.setView([points[id]._latlng.lat + diff, points[id]._latlng.lng], myMap.getZoom()); if (showPopup) { marker.openPopup(); } history.pushState({pointId: id}, document.title, "/?point=" + id); document.title = marker.options.title; }); return true; } function setLayer(name) { if (layer) myMap.removeLayer(layers[layer]) layer = name; myMap.addLayer(layers[layer]); $('.layers').removeClass('selected'); $('.' + layer + 'Layer').addClass('selected'); $.cookie('mapLayer', layer); } function showArticle(id) { $.ajax({ url: "/json/article/id/" + id, success: function (data) { $('#articleModal').modal('hide').remove(); $('body').append($(data)); $('#articleModal').modal('show'); } }); } function showPointagreement() { $.ajax({ url: "/json/pointagreement", success: function (data) { $('#articleModal').modal('hide').remove(); $('body').append($(data)); $('#articleModal').modal('show'); } }); }