wikipoints/public/js/route.js

218 lines
4.9 KiB
JavaScript
Raw Permalink 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.

/*
* Набор функций для работы с маршрутами.
*/
/**
* Строит маршрут по выбранным точкам.
* @returns {undefined}
*/
function buildRoute(fit)
{
wayPoints = Array();
$('#wayPoints div').each(function(i, el)
{
if ($(el).attr('pointId').length <= 10) {
lat = points[$(el).attr('pointId')]._latlng.lat;
lng = points[$(el).attr('pointId')]._latlng.lng;
wayPoints.push({latLng: points[$(el).attr('pointId')]._latlng});
} else {
coords = JSON.parse($(el).attr('pointId'));
lat = coords[0];
lng = coords[1];
wayPoints.push({latLng: {lat: lat, lng: lng}});
costomPointName = 'c_'+lat+'_'+lng;
if (typeof points[costomPointName] == 'undefined') {
points[costomPointName] = L.marker([lat, lng], {icon: categories.simplepoint, title: 'Произвольная точка'});
markers.addLayer(points[costomPointName]);
}
}
});
if (wayPoints.length > 1)
{
if (route) {
route.setWaypoints([])
}
route = L.Routing.control({waypoints: wayPoints,
lineOptions:
{styles: [
{color: 'black', opacity: 0.5, weight: 9},
{color: 'green', opacity: 0.7, weight: 7},
{color: 'orange', opacity: 1, weight: 3}]},
fitSelectedRoutes: (fit === true),
createMarker: function () {
return null;
}});
route.on('routesfound', function (e) {
distance = Math.round(e.routes[0].summary.totalDistance / 1000);
$('#routeDistance').html('Протяженность <b>' + distance + '</b> км.');
route.addTo(myMap);
route.hide();
});
route.on('routingerror', function (e) {
alert('Произошла ошибка. Вероятно построить маршрут по выбранным точкам невозможно.');
});
if (typeof yaCounter24682772 != 'undefined') {
yaCounter24682772.reachGoal('BUILD_ROUTE');
}
routeToURL();
}
}
/**
* Сохраняет маршрут на сервере.
* @returns {undefined}
*/
function saveRoute()
{
wayPoints = Array();
name = prompt('Как назвать маршрут?', 'Мой маршрут');
$('#wayPoints div').each(function(i, el)
{
wayPoints.push($(el).attr('pointId'));
});
if (name && name != '')
$.ajax({
type: "POST",
url: "/json/saveroute/",
data: {
name: name,
points: wayPoints
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
}
/**
* Формирует список точек маршрута из JSON.ы
* @param {JSON} data
* @returns {Boolean}
*/
function loadRouteJSON(data)
{
$('#wayPoints').text('');
response = JSON.parse(data);
for (var k in response)
{
if (response[k].length >= 10) {
response[k] = JSON.parse(response[k]);
}
addToRoute(response[k], false);
}
return true;
}
/**
* Подгружает маршрут с заданныи ID с сервера.
* @param {Integer} id
* @returns {undefined}
*/
function loadRoute(id)
{
openBox('Route')
$.ajax({
url: "/json/route/id/" + id,
success: function(data)
{
loadRouteJSON(data)
buildRoute();
}
});
}
/**
* Удаляет маршрут с заданным ID с сервера.
* @param {Integer} id
* @returns {undefined}
*/
function deleteRoute(id)
{
$.ajax({
url: "/json/deleteroute/id/" + id,
success: function(data)
{
console.log('Route '+id+' was removed.');
}
});
}
/**
* Добавляет точку с маршрут (в список выбранных точек)
* @param {Integer} id
* @returns {Boolean}
*/
function addToRoute(id, build)
{
$('#routeInfo').remove();
if ($.isArray(id)) {
n = (id[0]>=0) ? 'N'+id[0] : 'S'+Math.abs(id[0]);
e = (id[1]>=0) ? 'E'+id[1] : 'W'+Math.abs(id[1]);
coordsName = n.substring(0,10)+'° '+e.substring(0,10)+'°';
costomPointName = 'c_'+id[0]+'_'+id[1];
$('#wayPoints').append('<div pointid="'+JSON.stringify(id)+'" class="wayPoint"><span class="del" onclick="$(this).parent().remove();myMap.removeLayer(points[\''+costomPointName+'\']);buildRoute();">&times;</span> '+coordsName+'</div>');
closePopup();
openBox('Route', true);
if (build !== false) {
buildRoute();
}
return true;
} else {
$('#wayPoints').append('<div pointid="' + id + '" class="wayPoint" onclick="showInfo('+ id +');"><span class="del" onclick="$(this).parent().remove();buildRoute();">&times;</span> '+ points[id].options.title + '</div>');
closePopup();
openBox('Route', true);
if (build !== false)
buildRoute();
return true;
}
}
/**
* Формирует URL в соответсвии с точками маршрута.
* @returns {Boolean}
*/
function routeToURL()
{
wayPoints = Array();
$('#wayPoints div').each(function(i, el)
{
wayPoints.push($(el).attr('pointId'));
});
history.pushState({route: JSON.stringify(wayPoints)}, document.title, "/?route=" + JSON.stringify(wayPoints));
$('#printRoute').attr('href', "/index/route/?route=" + JSON.stringify(wayPoints));
return true;
}