wikipoints/public/js/map.js

255 lines
8.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* 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;
categories.im = L.icon({
iconUrl: '/ico/man.png',
iconSize: [32, 37],
iconAnchor: [16, 37],
popupAnchor: [0, 1]
});
// -----------------------------------------------------------------------------
/**
* Инициализируем яндекс-карты и узнаём расположение пользователя.
*/
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('<b>Ваше местоположение</b><br/><img src="/ico/man.png" /> <button type="button" class="btn btn-default btn-xs" onclick="addToRoute(\'im\')"><span class="glyphicon glyphicon-plus"></span> Добавить в маршрут</button>');
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 &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 18});
layers['osm'] = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery ©</a>', maxZoom: 18});
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()
});
return true;
}
/**
* Создаёт точку для карты - Placemark.
* @param {Array} data
* @returns {Array}
*/
function constructPoint(data)
{
id = data['id'];
points[id] = L.marker(
[data['lat'], data['lng']], {icon: categories[data['categoryId']], title: data['name'], id: id, categoryId: data['categoryId']}
).on('click', function (e) {
showInfo(e.target.options.id);
});
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)
{
marker = points[id];
if (!(id in points) || marker.options.description == undefined)
{
marker.bindPopup("Загрузка...").openPopup();
$.ajax({
url: "/json/point/id/" + id,
success: function (data) {
pointsSources[id] = data;
if (typeof (data.images) == 'object')
{
photos = '<div style="position: relative;">';
if (data.images.length > 1)
photos += '<div class="photosCount"><span class="glyphicon glyphicon-camera"></span> <b>+' + (data.photosCount - 1) + '</b></div>';
photos += '<img src="/photos/small/' + data.img + '" onclick="showImage(\'' + id + '\')" />';
photos += '</div>';
}
else
{
photos = '<img src="' + data.img + '" onclick="showImage(\'' + id + '\')" />';
}
description = '<div class="infoCard">' + '<h3>' + data.name + '</h3>' + photos;
description += data.descriptionHtml;
description += '</div><div class="clear"></div>';
description += '<div class="btn-group control">';
description += '<a type="button" class="btn btn-default" href="/page/point/id/' + id + '"><span class="glyphicon glyphicon-eye-open"></span> <span class="label">Подробнее</span></a>';
description += '<button type="button" class="btn btn-default" onclick="addToRoute(' + id + ')"><span class="glyphicon glyphicon-map-marker"></span> <span class="label">В маршрут</span></button>';
description += '<button type="button" class="btn btn-default" onclick="addRemoveLike(' + id + ')"><span id="myLikesButton" class="glyphicon glyphicon-' + (data.iLike ? 'ok' : 'thumbs-up') + '"></span> <span class="label">Нравится</span></button>';
description += '<button type="button" class="btn btn-default" onclick="addRemoveFavorite(' + id + ')"><span id="myFavoritesButton" class="glyphicon glyphicon-star' + (data.inFavorites ? '' : '-empty') + ' "></span> <span class="label">Хочу посетить</span></button>';
if (isAdmin == '1')
{
description += '<button type="button" class="btn btn-default" onclick="editPoint(' + id + ')"><span class="glyphicon glyphicon-pencil"></span> <span class="label">Редактировать</span></button>';
}
description += '</div>';
marker.options.description = description;
marker.bindPopup(marker.options.description, {maxWidth: 500, maxHeight: 300});
markers.zoomToShowLayer(marker, function () {
marker.openPopup();
bounds = myMap.getBounds();
diff = (bounds._northEast.lat - bounds._southWest.lat) / 4;
myMap.setView([points[id]._latlng.lat + diff, points[id]._latlng.lng], myMap.getZoom());
history.pushState({pointId: id}, document.title, "/?point=" + id);
document.title = data.name;
});
}
});
} else {
bounds = myMap.getBounds();
diff = (bounds._northEast.lat - bounds._southWest.lat) / 4;
myMap.setView([points[id]._latlng.lat + diff, points[id]._latlng.lng], myMap.getZoom());
history.pushState({pointId: id}, document.title, "/?point=" + id);
document.title = points[id].options.title;
// marker.openPopup();
}
}
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);
}