wikipoints/public/js/main.js

284 lines
8.3 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!
*/
ymaps.ready(init);
var myMap;
var categories;
var points = Array();
var im;
var search;
// -------------------------------- Libs ---------------------------------------
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// -----------------------------------------------------------------------------
function init() {
myMap = new ymaps.Map("map", {
center: [ymaps.geolocation.latitude, ymaps.geolocation.longitude],
zoom: 12,
behaviors: ['default', 'scrollZoom']
});
myMap.controls.add('mapTools');
myMap.controls.add('typeSelector');
myMap.controls.add('smallZoomControl');
myMap.controls.add('scaleLine');
initCategories()
getPoints();
myMap.events.add('click', function (e) {
if (!myMap.balloon.isOpen()) {
if ( $('#addPointButton').hasClass('btn-success') )
{
coords = e.get('coordPosition');
$('#addPointLat').val(coords[0].toPrecision(11));
$('#addPointLng').val(coords[1].toPrecision(11));
$('#addPointModal').modal('show');
}
}
else {
myMap.balloon.close();
}
});
im = new ymaps.Placemark(
[ymaps.geolocation.latitude, ymaps.geolocation.longitude],
{
balloonContentHeader: 'Вы здесь',
balloonContent: ''
},
{
iconImageHref: '/ico/man.png',
iconImageSize: [32, 37],
iconImageOffset: [-16, -33],
}
);
myMap.geoObjects.add(im);
}
function constructPoint(data)
{
id = data['id'];
points[id] = new ymaps.Placemark(
[data['lat'], data['lng']], {
hintContent: data['name'],
id: id
},
{
iconImageHref: data['categoryIcon'],
iconImageSize: [32, 37],
iconImageOffset: [-16, -33],
openEmptyBalloon: true,
balloonCloseButton: true
});
points[id].events.add('click', function (e) {
showInfo(e.get('target').properties.get('id'));
});
return points[id];
}
function getPoints()
{
$.ajax({
url: "/json/points/",
success: function(data){
for(var k in data) {
myMap.geoObjects.add(constructPoint(data[k]));
}
if (getURLParameter('point') != 'null')
{
showInfo(getURLParameter('point'));
}
}
});
return true;
}
function showInfo(id)
{
if (!(id in points) || points[id].properties.get('balloonContent') == undefined)
{
points[id].properties.set('balloonContent', 'Загрузка...');
$.ajax({
url: "/json/point/id/" + id,
success: function(data) {
description = '<div class="infoCard">' +
'<a href="/?point='+id+'">' +
'<h3>' + data.name + '</h3>' +
'</a>' +
'<img src="' + data.img + '" />' +
'<button type="button" class="btn btn-default btn-xs" onclick="addToRoute(' + id + ')">' +
'<span class="glyphicon glyphicon-plus"></span> Добавить в маршрут' +
'</button><br/>' +
data.description +
' <a href="' + data.source + '" target="blank">Подробнее...</a></div>'
points[id].properties.set('balloonContent', description);
point = getURLParameter('point');
if (point != null && id == point)
{
points[point].balloon.open();
}
}
});
}
history.pushState({}, document.title, "/?point="+id);
return true;
}
function initCategories()
{
$.ajax({
url: "/json/categories/",
success: function(data){
categories = data;
}
});
return true;
}
function searchAdderess()
{
var myGeocoder = ymaps.geocode($('#addressField').val());
myGeocoder.then(
function (res) {
search = new ymaps.Placemark(res.geoObjects.get(0).geometry.getCoordinates());
myMap.geoObjects.add(search);
myMap.setCenter(res.geoObjects.get(0).geometry.getCoordinates(), 10);
},
function (err) {}
);
}
function showMeOnTheMap()
{
navigator.geolocation.getCurrentPosition(function(pos) {
im.geometry.setCoordinates([pos.coords.latitude, pos.coords.longitude]);
myMap.setCenter(im.geometry.getCoordinates());
});
myMap.setCenter(im.geometry.getCoordinates());
}
function activateAddPoint()
{
$('#addPointButton').toggleClass('btn-success').toggleClass('btn-default');
if ( $('#addPointButton').hasClass('btn-success') )
myMap.cursors.push('crosshair');
else
myMap.cursors.push('arrow');
}
function addPoint()
{
$('.form-group').removeClass('has-error');
$.ajax({
type: "POST",
url: "/json/addpoint/",
data: {
name: $('#addPointName').val(),
img: $('#addPointImg').val(),
description: $('#addPointDescription').val(),
categoryId: $('#addPointCategoryId').val(),
source: $('#addPointSource').val(),
lat: $('#addPointLat').val(),
lng: $('#addPointLng').val()
},
success: function(data) {
balloon = myMap.balloon.open([$('#addPointLat').val(), $('#addPointLng').val()], {content: 'Точка успешно добавлена!'}, {closeButton: false});
setTimeout(function() {
balloon.close();
}, 3000);
obj = {};
obj.id = data;
obj.name = $('#addPointName').val();
obj.lat = $('#addPointLat').val();
obj.lng = $('#addPointLng').val();
obj.categoryIcon = categories[$('#addPointCategoryId').val()].icon;
setTimeout(function(){
myMap.geoObjects.add(constructPoint(obj));
}, 3000);
$('#addPointModal').modal('hide');
// Clear form
$('#addPointForm input').val('');
$('#addPointForm textarea').val('');
$('.form-group').removeClass('has-error');
$('#addPointButton').removeClass('btn-success').addClass('btn-default');
myMap.cursors.push('arrow');
},
error: function(data) {
response = data.responseJSON;
message = '';
for (var k in response) {
if (typeof response[k] !== 'function') {
if (k == 1)
$('#addPointName').parent().addClass('has-error');
else
if (k == 2)
$('#addPointImg').parent().addClass('has-error');
else
if (k == 3)
$('#addPointDescription').parent().addClass('has-error');
else
message += response[k] + '; ';
}
}
if (message != '')
alert(message);
}
});
}
function buildRoute()
{
wayPoints = Array();
$('#wayPoints li').each(function(i, el)
{
wayPoints.push(points[$(el).attr('pointId')].geometry.getCoordinates());
});
ymaps.route(wayPoints, {
mapStateAutoApply: true
}).then(function(route) {
// console.log(route.getPaths());
route.options.set({
// в балуне выводим только информацию о времени движения с учетом пробок
balloonContenBodyLayout: ymaps.templateLayoutFactory.createClass('$[properties.humanJamsTime]'),
strokeColor: '9000ffff',
opacity: 0.9
});
myMap.geoObjects.add(route);
distance = Math.round(route.getLength() / 1000);
$('#routeDistance').text(distance + ' км.')
});
}
function addToRoute(id)
{
$('#wayPoints').append('<li pointid="'+id+'">' + points[id].properties.get('hintContent') + '</li>');
myMap.balloon.close();
$('#routeWindow').show(200);
return true;
}