Передача роутов в урле, без сохранения на сервере.

This commit is contained in:
Krivchikov Dmitry 2014-05-10 21:44:16 +04:00
parent 5dc486e22d
commit 4b01c9dccf
1 changed files with 114 additions and 11 deletions

View File

@ -17,6 +17,10 @@ function getURLParameter(name) {
// -----------------------------------------------------------------------------
/**
* Инициализируем переменные и подгружаем данные.
* @returns true
*/
function init() {
myMap = new ymaps.Map("map", {
center: [ymaps.geolocation.latitude, ymaps.geolocation.longitude],
@ -48,7 +52,8 @@ function init() {
});
myMap.events.add('boundschange', function(e) {
if (!myMap.balloon.isOpen()) {
if (!myMap.balloon.isOpen() && $('#routeWindow').css('display') == 'none')
{
history.pushState({}, document.title, "/?lat=" + e.get('newCenter')[0] + "&lng=" + e.get('newCenter')[1] + "&zoom=" + e.get('newZoom'));
}
});
@ -73,8 +78,15 @@ function init() {
$("#wayPoints").sortable();
$("#wayPoints").disableSelection();
return true;
}
/**
* Создаёт точку для карту - Placemark.
* @param {Array} data
* @returns {ymaps.Placemark}
*/
function constructPoint(data)
{
id = data['id'];
@ -98,6 +110,10 @@ function constructPoint(data)
return points[id];
}
/**
* Загружает точки с сервера.
* @returns {Boolean}
*/
function getPoints()
{
$.ajax({
@ -110,6 +126,10 @@ function getPoints()
if (getURLParameter('point') != 'null')
{
showInfo(getURLParameter('point'));
} else if (getURLParameter('route') != 'null')
{
loadRouteJSON(getURLParameter('route'));
buildRoute();
} else if ((getURLParameter('lat') != 'null') && (getURLParameter('lng') != 'null') && (getURLParameter('zoom') != 'null'))
{
myMap.setCenter([getURLParameter('lat'), getURLParameter('lng')], getURLParameter('zoom'));
@ -120,6 +140,11 @@ function getPoints()
return true;
}
/**
* Показывает баллун для точки. Если данных для точки нет, то подгружает их с сервера.
* @param {type} id
* @returns {Boolean}
*/
function showInfo(id)
{
if (!(id in points) || points[id].properties.get('balloonContent') == undefined)
@ -153,6 +178,10 @@ function showInfo(id)
return true;
}
/**
* Загружает с сервера список категорий точек.
* @returns {Boolean}
*/
function initCategories()
{
$.ajax({
@ -165,6 +194,10 @@ function initCategories()
return true;
}
/**
* Производит поиск по адресу или координатам, введённым в соответствующее поле.
* @returns {undefined}
*/
function searchAdderess()
{
var myGeocoder = ymaps.geocode($('#addressField').val());
@ -179,6 +212,10 @@ function searchAdderess()
);
}
/**
* Пытается более точно определить координаты пользователя на карте и, при необходимости, обновляет положение точки "im"
* @returns {undefined}
*/
function showMeOnTheMap()
{
navigator.geolocation.getCurrentPosition(function(pos) {
@ -189,6 +226,10 @@ function showMeOnTheMap()
myMap.setCenter(points.im.geometry.getCoordinates());
}
/**
* Активирет добавление точки - ждёт выбор координат, меняет курсор на прицел.
* @returns {Boolean}
*/
function activateAddPoint()
{
$('#addPointButton').toggleClass('btn-success').toggleClass('btn-default');
@ -196,8 +237,14 @@ function activateAddPoint()
myMap.cursors.push('crosshair');
else
myMap.cursors.push('arrow');
return true;
}
/**
* Отправляет данные по новой точке на сервер.
* @returns {Boolean}
*/
function addPoint()
{
$('.form-group').removeClass('has-error');
@ -238,6 +285,8 @@ function addPoint()
$('.form-group').removeClass('has-error');
$('#addPointButton').removeClass('btn-success').addClass('btn-default');
myMap.cursors.push('arrow');
return true;
},
error: function(data) {
response = data.responseJSON;
@ -259,10 +308,16 @@ function addPoint()
if (message != '')
alert(message);
return false;
}
});
}
/**
* Строит маршрут по выбранным точкам.
* @returns {undefined}
*/
function buildRoute()
{
wayPoints = Array();
@ -287,10 +342,15 @@ function buildRoute()
myMap.geoObjects.add(route);
distance = Math.round(route.getLength() / 1000);
$('#routeDistance').text(distance + ' км.')
$('#routeDistance').text(distance + ' км.');
routeToURL();
});
}
/**
* Сохраняет маршрут на сервере.
* @returns {undefined}
*/
function saveRoute()
{
wayPoints = Array();
@ -318,6 +378,29 @@ function saveRoute()
});
}
/**
* Формирует список точек маршрута из JSON.ы
* @param {JSON} data
* @returns {Boolean}
*/
function loadRouteJSON(data)
{
$('#wayPoints').text('');
response = JSON.parse(data);
for (var k in response)
{
addToRoute(response[k]);
}
return true;
}
/**
* Подгружает маршрут с заданныи ID с сервера.
* @param {Integer} id
* @returns {undefined}
*/
function loadRoute(id)
{
$('#myRoutesWindow').hide(200);
@ -326,19 +409,17 @@ function loadRoute(id)
url: "/json/route/id/" + id,
success: function(data)
{
$('#wayPoints').text('');
response = JSON.parse(data);
for (var k in response)
{
addToRoute(response[k]);
}
loadRouteJSON(data)
buildRoute();
}
});
}
/**
* Удаляет маршрут с заданным ID с сервера.
* @param {Integer} id
* @returns {undefined}
*/
function deleteRoute(id)
{
$.ajax({
@ -350,7 +431,11 @@ function deleteRoute(id)
});
}
/**
* Добавляет точку с маршрут (в список выбранных точек)
* @param {Integer} id
* @returns {Boolean}
*/
function addToRoute(id)
{
$('#wayPoints').append('<div pointid="' + id + '" class="wayPoint"><span onclick="$(this).parent().remove()">&times;</span> ' + points[id].properties.get('hintContent') + '</div>');
@ -358,3 +443,21 @@ function addToRoute(id)
$('#routeWindow').show(200);
return true;
}
/**
* Формирует URL в соответсвии с точками маршрута.
* @returns {Boolean}
*/
function routeToURL()
{
wayPoints = Array();
$('#wayPoints div').each(function(i, el)
{
wayPoints.push($(el).attr('pointId'));
});
history.pushState({}, document.title, "/?route=" + JSON.stringify(wayPoints));
return true;
}