<?php
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Extension\SandboxExtension;
use Twig\Markup;
use Twig\Sandbox\SecurityError;
use Twig\Sandbox\SecurityNotAllowedTagError;
use Twig\Sandbox\SecurityNotAllowedFilterError;
use Twig\Sandbox\SecurityNotAllowedFunctionError;
use Twig\Source;
use Twig\Template;
/* Map/page.html.twig */
class __TwigTemplate_4be02f91027edecd6d364d2dec5094bd extends Template
{
private $source;
private $macros = [];
public function __construct(Environment $env)
{
parent::__construct($env);
$this->source = $this->getSourceContext();
$this->blocks = [
'mainContainer' => [$this, 'block_mainContainer'],
'javascripts' => [$this, 'block_javascripts'],
];
}
protected function doGetParent(array $context)
{
// line 1
return "grid.html.twig";
}
protected function doDisplay(array $context, array $blocks = [])
{
$macros = $this->macros;
$__internal_b91a4435ea3baf1e2b6bfda56133dace = $this->extensions["Sentry\\SentryBundle\\Tracing\\Twig\\TwigTracingExtension"];
$__internal_b91a4435ea3baf1e2b6bfda56133dace->enter($__internal_b91a4435ea3baf1e2b6bfda56133dace_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "template", "Map/page.html.twig"));
$__internal_5a27a8ba21ca79b61932376b2fa922d2 = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"];
$__internal_5a27a8ba21ca79b61932376b2fa922d2->enter($__internal_5a27a8ba21ca79b61932376b2fa922d2_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "template", "Map/page.html.twig"));
$__internal_6f47bbe9983af81f1e7450e9a3e3768f = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"];
$__internal_6f47bbe9983af81f1e7450e9a3e3768f->enter($__internal_6f47bbe9983af81f1e7450e9a3e3768f_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "template", "Map/page.html.twig"));
$this->parent = $this->loadTemplate("grid.html.twig", "Map/page.html.twig", 1);
$this->parent->display($context, array_merge($this->blocks, $blocks));
$__internal_b91a4435ea3baf1e2b6bfda56133dace->leave($__internal_b91a4435ea3baf1e2b6bfda56133dace_prof);
$__internal_5a27a8ba21ca79b61932376b2fa922d2->leave($__internal_5a27a8ba21ca79b61932376b2fa922d2_prof);
$__internal_6f47bbe9983af81f1e7450e9a3e3768f->leave($__internal_6f47bbe9983af81f1e7450e9a3e3768f_prof);
}
// line 3
public function block_mainContainer($context, array $blocks = [])
{
$macros = $this->macros;
$__internal_b91a4435ea3baf1e2b6bfda56133dace = $this->extensions["Sentry\\SentryBundle\\Tracing\\Twig\\TwigTracingExtension"];
$__internal_b91a4435ea3baf1e2b6bfda56133dace->enter($__internal_b91a4435ea3baf1e2b6bfda56133dace_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "mainContainer"));
$__internal_5a27a8ba21ca79b61932376b2fa922d2 = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"];
$__internal_5a27a8ba21ca79b61932376b2fa922d2->enter($__internal_5a27a8ba21ca79b61932376b2fa922d2_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "mainContainer"));
$__internal_6f47bbe9983af81f1e7450e9a3e3768f = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"];
$__internal_6f47bbe9983af81f1e7450e9a3e3768f->enter($__internal_6f47bbe9983af81f1e7450e9a3e3768f_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "mainContainer"));
// line 4
echo " ";
// line 5
echo " <div id=\"map_form\"></div>
<p>
<button type=\"button\" id=\"map_refresh\" disabled>Обновить карту</button>
<button type=\"button\" id=\"map_reset\" disabled>Сбросить фильтры</button>
<span id=\"map_status\" role=\"status\" aria-live=\"polite\">Загрузка карты…</span>
</p>
<img src=\"";
// line 11
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\AssetExtension']->getAssetUrl("/static/preloader.gif"), "html", null, true);
echo "\" id=\"preloader\" style=\"display: none;\" />
<div id=\"map\"
data-city-uri-idenity=\"";
// line 13
echo twig_escape_filter($this->env, (isset($context["cityUriIdentity"]) || array_key_exists("cityUriIdentity", $context) ? $context["cityUriIdentity"] : (function () { throw new RuntimeError('Variable "cityUriIdentity" does not exist.', 13, $this->source); })()), "html", null, true);
echo "\"
data-city-latitude=\"";
// line 14
echo twig_escape_filter($this->env, (isset($context["cityLatitude"]) || array_key_exists("cityLatitude", $context) ? $context["cityLatitude"] : (function () { throw new RuntimeError('Variable "cityLatitude" does not exist.', 14, $this->source); })()), "html", null, true);
echo "\"
data-city-longitude=\"";
// line 15
echo twig_escape_filter($this->env, (isset($context["cityLongitude"]) || array_key_exists("cityLongitude", $context) ? $context["cityLongitude"] : (function () { throw new RuntimeError('Variable "cityLongitude" does not exist.', 15, $this->source); })()), "html", null, true);
echo "\"
data-map-context=\"";
// line 16
echo twig_escape_filter($this->env, (isset($context["mapContext"]) || array_key_exists("mapContext", $context) ? $context["mapContext"] : (function () { throw new RuntimeError('Variable "mapContext" does not exist.', 16, $this->source); })()), "html", null, true);
echo "\"
style=\"width:100%; height:500px;\"></div>
";
$__internal_6f47bbe9983af81f1e7450e9a3e3768f->leave($__internal_6f47bbe9983af81f1e7450e9a3e3768f_prof);
$__internal_5a27a8ba21ca79b61932376b2fa922d2->leave($__internal_5a27a8ba21ca79b61932376b2fa922d2_prof);
$__internal_b91a4435ea3baf1e2b6bfda56133dace->leave($__internal_b91a4435ea3baf1e2b6bfda56133dace_prof);
}
// line 20
public function block_javascripts($context, array $blocks = [])
{
$macros = $this->macros;
$__internal_b91a4435ea3baf1e2b6bfda56133dace = $this->extensions["Sentry\\SentryBundle\\Tracing\\Twig\\TwigTracingExtension"];
$__internal_b91a4435ea3baf1e2b6bfda56133dace->enter($__internal_b91a4435ea3baf1e2b6bfda56133dace_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "javascripts"));
$__internal_5a27a8ba21ca79b61932376b2fa922d2 = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"];
$__internal_5a27a8ba21ca79b61932376b2fa922d2->enter($__internal_5a27a8ba21ca79b61932376b2fa922d2_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "javascripts"));
$__internal_6f47bbe9983af81f1e7450e9a3e3768f = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"];
$__internal_6f47bbe9983af81f1e7450e9a3e3768f->enter($__internal_6f47bbe9983af81f1e7450e9a3e3768f_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "javascripts"));
// line 21
echo " <script src=\"";
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\AssetExtension']->getAssetUrl("bundles/fosjsrouting/js/router.min.js"), "html", null, true);
echo "\"></script>
<script src=\"";
// line 22
echo $this->extensions['Symfony\Bridge\Twig\Extension\RoutingExtension']->getPath("fos_js_routing_js", ["callback" => "fos.Router.setData"]);
echo "\"></script>
<script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>
<script src=\"https://api-maps.yandex.ru/2.1/?lang=ru_RU\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
;var RoutingDecorator = {
generate: function (name, params) {
const orig_name = name;
try {
Routing.getRoute(name)
} catch(error) {
name = name + '.' + '";
// line 33
echo twig_escape_filter($this->env, twig_get_attribute($this->env, $this->source, twig_get_attribute($this->env, $this->source, (isset($context["app"]) || array_key_exists("app", $context) ? $context["app"] : (function () { throw new RuntimeError('Variable "app" does not exist.', 33, $this->source); })()), "request", [], "any", false, false, false, 33), "locale", [], "any", false, false, false, 33), "html", null, true);
echo "';
try {
Routing.getRoute(name)
} catch(error) {
name = orig_name;
}
}
return Routing.generate(name, params);
}
};
;(function () {
document.addEventListener('DOMContentLoaded', _ => {
var avatarPath = '";
// line 48
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\AssetExtension']->getAssetUrl("", "profile_media_avatar"), "html", null, true);
echo "';
var photoPath = '";
// line 49
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\AssetExtension']->getAssetUrl("", "profile_media"), "html", null, true);
echo "';
var thumbPath = '";
// line 50
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\AssetExtension']->getAssetUrl("", "saloon_media_thumb"), "html", null, true);
echo "';
var mapContainer = document.querySelector('#map');
var preloader = document.querySelector('#preloader');
var refreshButton = document.querySelector('#map_refresh');
var resetButton = document.querySelector('#map_reset');
var mapStatus = document.querySelector('#map_status');
var loading = false;
var mapContext = mapContainer.getAttribute('data-map-context');
var cityUriIdentity = mapContainer.getAttribute('data-city-uri-idenity');
var cityLatitude = mapContainer.getAttribute('data-city-latitude');
var cityLongitude = mapContainer.getAttribute('data-city-longitude');
var formName = 'filter_map_form';
var multipleCities = ";
// line 62
echo twig_escape_filter($this->env, (isset($context["multipleCities"]) || array_key_exists("multipleCities", $context) ? $context["multipleCities"] : (function () { throw new RuntimeError('Variable "multipleCities" does not exist.', 62, $this->source); })()), "html", null, true);
echo ";
var routesUrl = '/js/fos_js_routes";
// line 63
echo (((isset($context["multipleCities"]) || array_key_exists("multipleCities", $context) ? $context["multipleCities"] : (function () { throw new RuntimeError('Variable "multipleCities" does not exist.', 63, $this->source); })())) ? ("_city_prefixed") : (""));
echo ".json';
if (typeof ymaps === 'undefined') {
mapStatus.textContent = 'Не удалось загрузить Яндекс.Карты. Перезагрузите страницу.';
return;
}
var mapLoadTimeout = setTimeout(() => {
mapStatus.textContent = 'Не удалось загрузить Яндекс.Карты. Перезагрузите страницу.';
}, 15000);
loadRoutes();
var myMap, clusterer;
ymaps.ready(function () {
clearTimeout(mapLoadTimeout);
myMap = new ymaps.Map('map', {
center: [cityLatitude, cityLongitude],
zoom: 9,
behaviors: ['default', 'scrollZoom']
}, {
searchControlProvider: 'yandex#search'
});
clusterer = new ymaps.Clusterer({
preset: 'islands#invertedVioletClusterIcons',//Через кластеризатор можно указать только стили кластеров,стили для меток нужно назначать каждой метке отдельно.
groupByCoordinates: false,//Ставим true, если хотим кластеризовать только точки с одинаковыми координатами.
//Опции кластеров указываем в кластеризаторе с префиксом \"cluster\".
clusterDisableClickZoom: true,
clusterHideIconOnBalloonOpen: false,
geoObjectHideIconOnBalloonOpen: false
});
// Можно менять опции кластеризатора после создания.
clusterer.options.set({
gridSize: 80,
clusterDisableClickZoom: true
});
loadForm();
refreshButton.addEventListener('click', function () {
if (document.querySelector('form[name=\"' + formName + '\"]')) {
filterData();
} else {
loadForm();
}
});
resetButton.addEventListener('click', function () {
document.querySelector('form[name=\"' + formName + '\"]').reset();
filterData();
});
});
function loadRoutes() {
\$.ajax({
url:routesUrl,
dataType: \"json\",
async: false,
success: function (routes) {
Routing.setRoutingData(routes);
},
error: function (xhr, ajaxOptions, thrownError) {}
});
}
function setFormSubmitListener() {
document.querySelector(\"form[name=\"+formName+\"]\").addEventListener('submit', function(e){
e.preventDefault();
if(!clusterer)
return;
filterData();
return false;
});
}
function loadForm() {
setLoading(true);
fetch('";
// line 139
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\RoutingExtension']->getPath("map.form", ["city" => (isset($context["cityUriIdentity"]) || array_key_exists("cityUriIdentity", $context) ? $context["cityUriIdentity"] : (function () { throw new RuntimeError('Variable "cityUriIdentity" does not exist.', 139, $this->source); })())]), "html", null, true);
echo "', {
mode: \"cors\",
importance: \"low\",
method: \"POST\",
cache: 'no-store',
headers: {
\"Content-Type\": \"application/x-www-form-urlencoded\",
\"X-Requested-With\": \"XMLHttpRequest\"
},
body: new URLSearchParams({mapContext: mapContext}).toString(),
}).then(response => {
if (!response.ok) {
throw new Error('Cannot load map form');
}
return response.text();
}).then(response => {
document.querySelector('#map_form').innerHTML = response;
setFormSubmitListener();
setLoading(false);
filterData();
}).catch(() => {
showError();
setLoading(false);
});
}
function setLoading(value) {
loading = value;
preloader.style.display = value ? 'block' : 'none';
refreshButton.disabled = value;
resetButton.disabled = value || !document.querySelector('form[name=\"' + formName + '\"]');
if (value) {
mapStatus.textContent = 'Загрузка…';
}
}
function showError() {
mapStatus.textContent = 'Не удалось обновить карту. Нажмите «Обновить карту», чтобы повторить запрос.';
}
function filterData() {
if (loading) {
return;
}
setLoading(true);
var data = {};
\$(\"form[name=\"+formName+\"]\").serializeArray().forEach((object)=>{
//\"подгоняем\" данные под формат, ожидаемый формой при сабмите
var fieldName = object.name.toString().replace(formName + '[', '').replace(']', '');
var clearFieldName = fieldName.substr(0, fieldName.indexOf('['));
if(~fieldName.indexOf('[]')) {
checkArrayIsInFormObject(clearFieldName, data);
data[clearFieldName].push(object.value);
} else if(~fieldName.indexOf('[m')) {
if(!object.value)
return;
checkObjectIsInFormObject(clearFieldName, data);
if(~fieldName.indexOf('[min]'))
data[clearFieldName]['min'] = object.value;
if(~fieldName.indexOf('[max]'))
data[clearFieldName]['max'] = object.value;
} else {
data[fieldName] = object.value;
}
});
\$.ajax({
url:'";
// line 209
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\RoutingExtension']->getPath("map.filter", ["city" => (isset($context["cityUriIdentity"]) || array_key_exists("cityUriIdentity", $context) ? $context["cityUriIdentity"] : (function () { throw new RuntimeError('Variable "cityUriIdentity" does not exist.', 209, $this->source); })())]), "html", null, true);
echo "',
type: \"POST\",
dataType: \"json\",
cache: false,
data: {
\"form\": JSON.stringify(data),
\"mapContext\": mapContext,
\"scale\": myMap.getZoom(),
},
async: true,
}).then(getDetailsData).then(points => {
updateMap(points);
mapStatus.textContent = 'Анкеты: ' + points.profiles.length + '. Салоны: ' + points.saloons.length + '.';
}).catch(showError).always(() => setLoading(false));
}
function checkArrayIsInFormObject(name, formObject) {
if(false == formObject.hasOwnProperty(name))
formObject[name] = [];
}
function checkObjectIsInFormObject(name, formObject) {
if(false == formObject.hasOwnProperty(name))
formObject[name] = {};
}
function getDetailsData(data) {
const profilesRawData = data.profiles || [];
const saloonsRawData = data.saloons || [];
const profilesAllId = profilesRawData.map(_data => _data[0]).flat();
const saloonsAllId = saloonsRawData.map(_data => _data[0]).flat();
const profileArray = Array.isArray(profilesAllId) ? profilesAllId : [];
const saloonIdArray = Array.isArray(saloonsAllId) ? saloonsAllId : [];
const requestBody = {};
requestBody.profiles = profileArray;
requestBody.saloons = saloonIdArray;
return fetch('";
// line 249
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\RoutingExtension']->getPath("map.detail", ["city" => (isset($context["cityUriIdentity"]) || array_key_exists("cityUriIdentity", $context) ? $context["cityUriIdentity"] : (function () { throw new RuntimeError('Variable "cityUriIdentity" does not exist.', 249, $this->source); })())]), "html", null, true);
echo "', {
method: \"POST\",
cache: 'no-store',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
},
body: new URLSearchParams(requestBody).toString()
})
.then(response => {
if (!response.ok) {
throw new Error('Cannot load map details');
}
return response.json();
});
}
function updateMap(points) {
clusterer.removeAll();
if (!points || (points.profiles.length == 0 && points.saloons.length == 0)) {
myMap.setCenter([cityLatitude, cityLongitude], 9);
return;
}
const mergedPoints = [...points.profiles, ...points.saloons];
var getImgUrl = function(path, imgType) {
if(path[0] == '/')
return path;
console.log(imgType)
console.log(photoPath)
console.log(thumbPath)
var assetPackagePath = '';
if(imgType == 'avatar')
assetPackagePath = avatarPath;
else if(imgType == 'photo')
assetPackagePath = photoPath; // /media/profiles/vp/rd/vprdP4ShlKUpkOB.jpg
else if(imgType == 'thumb')
assetPackagePath = thumbPath; // /media/saloons/thumb///.jpg
return `\${assetPackagePath}\${path.slice(0, 2).toLowerCase()}/\${path.slice(2, 4).toLowerCase()}/\${path}.jpg`;
};
var getPointData = function (point) {
const isProfile = point[0] == 1;
const isSaloon = point[0] == 2;
let url = '';
const uri = point[3];
if(isProfile) {
url = RoutingDecorator.generate(
'profile_preview.page',
multipleCities ? {city: cityUriIdentity, profile: uri} : {profile: uri}
);
} else if(isSaloon) {
url = RoutingDecorator.generate(
'saloon_preview.page',
multipleCities ? {city: cityUriIdentity, saloon: uri} : {saloon: uri}
);
}
var processProfileShowsUrl = '";
// line 312
echo twig_escape_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\RoutingExtension']->getPath("map.increment_profile_shows", (((isset($context["multipleCities"]) || array_key_exists("multipleCities", $context) ? $context["multipleCities"] : (function () { throw new RuntimeError('Variable "multipleCities" does not exist.', 312, $this->source); })())) ? (["city" => (isset($context["cityUriIdentity"]) || array_key_exists("cityUriIdentity", $context) ? $context["cityUriIdentity"] : (function () { throw new RuntimeError('Variable "cityUriIdentity" does not exist.', 312, $this->source); })())]) : ([]))), "html", null, true);
echo "';
return {
balloonContentHeader: '',
balloonContentBody: '<p><img src=\"' + getImgUrl(point[5], isProfile ? 'avatar' : 'thumb') + '\" width=\"100\" /></p>' + '<font size=3><b><a target=\"_blank\" href=\"' + url + '\">Профиль</a></b></font>'
+ '<img style=\"display:none;\" width=\"0\" height=\"0\" src=\"' + processProfileShowsUrl + '?id=' + (isProfile ? point[9] : null)+'\" />', //не убирать, функционально важно
balloonContentFooter: '<font size=1>' + point[8] + ',' + point[9] + ',' + point[10] + '</strong>',
clusterCaption: '<strong>' + (isSaloon ? 'Салон ' : '') + point[4] + '</strong>'
};
};
var getPointOptions = function (index, type) {
return {
preset: type == 'profile' ? 'islands#violetIcon' : 'islands#redIcon'
};
};
var geoObjects = [];
for(var i = 0, len = mergedPoints.length; i < len; i++) {
const _point = mergedPoints[i];
geoObjects[i] = new ymaps.Placemark([_point[1], _point[2]], getPointData(_point), getPointOptions(i, _point[0] == 1));
}
//В кластеризатор можно добавить javascript-массив меток (не геоколлекцию) или одну метку.
clusterer.add(geoObjects);
myMap.geoObjects.add(clusterer);
// Спозиционируем карту так, чтобы на ней были видны все объекты.
if (mergedPoints.length === 1) {
myMap.setCenter([mergedPoints[0][1], mergedPoints[0][2]], 14);
} else {
myMap.setBounds(clusterer.getBounds(), {
checkZoomRange: true,
zoomMargin: 40
}).then(() => {
if (myMap.getZoom() > 14) {
myMap.setZoom(14);
}
});
}
}
});
})();
</script>
";
$__internal_6f47bbe9983af81f1e7450e9a3e3768f->leave($__internal_6f47bbe9983af81f1e7450e9a3e3768f_prof);
$__internal_5a27a8ba21ca79b61932376b2fa922d2->leave($__internal_5a27a8ba21ca79b61932376b2fa922d2_prof);
$__internal_b91a4435ea3baf1e2b6bfda56133dace->leave($__internal_b91a4435ea3baf1e2b6bfda56133dace_prof);
}
/**
* @codeCoverageIgnore
*/
public function getTemplateName()
{
return "Map/page.html.twig";
}
/**
* @codeCoverageIgnore
*/
public function isTraitable()
{
return false;
}
/**
* @codeCoverageIgnore
*/
public function getDebugInfo()
{
return array ( 459 => 312, 393 => 249, 350 => 209, 277 => 139, 198 => 63, 194 => 62, 179 => 50, 175 => 49, 171 => 48, 153 => 33, 139 => 22, 134 => 21, 121 => 20, 105 => 16, 101 => 15, 97 => 14, 93 => 13, 88 => 11, 80 => 5, 78 => 4, 65 => 3, 36 => 1,);
}
public function getSourceContext()
{
return new Source("{% extends 'grid.html.twig' %}
{% block mainContainer %}
{# {{ form(form) }}#}
<div id=\"map_form\"></div>
<p>
<button type=\"button\" id=\"map_refresh\" disabled>Обновить карту</button>
<button type=\"button\" id=\"map_reset\" disabled>Сбросить фильтры</button>
<span id=\"map_status\" role=\"status\" aria-live=\"polite\">Загрузка карты…</span>
</p>
<img src=\"{{ asset('/static/preloader.gif') }}\" id=\"preloader\" style=\"display: none;\" />
<div id=\"map\"
data-city-uri-idenity=\"{{ cityUriIdentity }}\"
data-city-latitude=\"{{ cityLatitude }}\"
data-city-longitude=\"{{ cityLongitude }}\"
data-map-context=\"{{ mapContext }}\"
style=\"width:100%; height:500px;\"></div>
{% endblock %}
{% block javascripts %}
<script src=\"{{ asset('bundles/fosjsrouting/js/router.min.js') }}\"></script>
<script src=\"{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}\"></script>
<script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"></script>
<script src=\"https://api-maps.yandex.ru/2.1/?lang=ru_RU\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
;var RoutingDecorator = {
generate: function (name, params) {
const orig_name = name;
try {
Routing.getRoute(name)
} catch(error) {
name = name + '.' + '{{ app.request.locale }}';
try {
Routing.getRoute(name)
} catch(error) {
name = orig_name;
}
}
return Routing.generate(name, params);
}
};
;(function () {
document.addEventListener('DOMContentLoaded', _ => {
var avatarPath = '{{ asset('', 'profile_media_avatar') }}';
var photoPath = '{{ asset('', 'profile_media') }}';
var thumbPath = '{{ asset('', 'saloon_media_thumb') }}';
var mapContainer = document.querySelector('#map');
var preloader = document.querySelector('#preloader');
var refreshButton = document.querySelector('#map_refresh');
var resetButton = document.querySelector('#map_reset');
var mapStatus = document.querySelector('#map_status');
var loading = false;
var mapContext = mapContainer.getAttribute('data-map-context');
var cityUriIdentity = mapContainer.getAttribute('data-city-uri-idenity');
var cityLatitude = mapContainer.getAttribute('data-city-latitude');
var cityLongitude = mapContainer.getAttribute('data-city-longitude');
var formName = 'filter_map_form';
var multipleCities = {{ multipleCities }};
var routesUrl = '/js/fos_js_routes{{ multipleCities ? '_city_prefixed' }}.json';
if (typeof ymaps === 'undefined') {
mapStatus.textContent = 'Не удалось загрузить Яндекс.Карты. Перезагрузите страницу.';
return;
}
var mapLoadTimeout = setTimeout(() => {
mapStatus.textContent = 'Не удалось загрузить Яндекс.Карты. Перезагрузите страницу.';
}, 15000);
loadRoutes();
var myMap, clusterer;
ymaps.ready(function () {
clearTimeout(mapLoadTimeout);
myMap = new ymaps.Map('map', {
center: [cityLatitude, cityLongitude],
zoom: 9,
behaviors: ['default', 'scrollZoom']
}, {
searchControlProvider: 'yandex#search'
});
clusterer = new ymaps.Clusterer({
preset: 'islands#invertedVioletClusterIcons',//Через кластеризатор можно указать только стили кластеров,стили для меток нужно назначать каждой метке отдельно.
groupByCoordinates: false,//Ставим true, если хотим кластеризовать только точки с одинаковыми координатами.
//Опции кластеров указываем в кластеризаторе с префиксом \"cluster\".
clusterDisableClickZoom: true,
clusterHideIconOnBalloonOpen: false,
geoObjectHideIconOnBalloonOpen: false
});
// Можно менять опции кластеризатора после создания.
clusterer.options.set({
gridSize: 80,
clusterDisableClickZoom: true
});
loadForm();
refreshButton.addEventListener('click', function () {
if (document.querySelector('form[name=\"' + formName + '\"]')) {
filterData();
} else {
loadForm();
}
});
resetButton.addEventListener('click', function () {
document.querySelector('form[name=\"' + formName + '\"]').reset();
filterData();
});
});
function loadRoutes() {
\$.ajax({
url:routesUrl,
dataType: \"json\",
async: false,
success: function (routes) {
Routing.setRoutingData(routes);
},
error: function (xhr, ajaxOptions, thrownError) {}
});
}
function setFormSubmitListener() {
document.querySelector(\"form[name=\"+formName+\"]\").addEventListener('submit', function(e){
e.preventDefault();
if(!clusterer)
return;
filterData();
return false;
});
}
function loadForm() {
setLoading(true);
fetch('{{ path('map.form', {city: cityUriIdentity}) }}', {
mode: \"cors\",
importance: \"low\",
method: \"POST\",
cache: 'no-store',
headers: {
\"Content-Type\": \"application/x-www-form-urlencoded\",
\"X-Requested-With\": \"XMLHttpRequest\"
},
body: new URLSearchParams({mapContext: mapContext}).toString(),
}).then(response => {
if (!response.ok) {
throw new Error('Cannot load map form');
}
return response.text();
}).then(response => {
document.querySelector('#map_form').innerHTML = response;
setFormSubmitListener();
setLoading(false);
filterData();
}).catch(() => {
showError();
setLoading(false);
});
}
function setLoading(value) {
loading = value;
preloader.style.display = value ? 'block' : 'none';
refreshButton.disabled = value;
resetButton.disabled = value || !document.querySelector('form[name=\"' + formName + '\"]');
if (value) {
mapStatus.textContent = 'Загрузка…';
}
}
function showError() {
mapStatus.textContent = 'Не удалось обновить карту. Нажмите «Обновить карту», чтобы повторить запрос.';
}
function filterData() {
if (loading) {
return;
}
setLoading(true);
var data = {};
\$(\"form[name=\"+formName+\"]\").serializeArray().forEach((object)=>{
//\"подгоняем\" данные под формат, ожидаемый формой при сабмите
var fieldName = object.name.toString().replace(formName + '[', '').replace(']', '');
var clearFieldName = fieldName.substr(0, fieldName.indexOf('['));
if(~fieldName.indexOf('[]')) {
checkArrayIsInFormObject(clearFieldName, data);
data[clearFieldName].push(object.value);
} else if(~fieldName.indexOf('[m')) {
if(!object.value)
return;
checkObjectIsInFormObject(clearFieldName, data);
if(~fieldName.indexOf('[min]'))
data[clearFieldName]['min'] = object.value;
if(~fieldName.indexOf('[max]'))
data[clearFieldName]['max'] = object.value;
} else {
data[fieldName] = object.value;
}
});
\$.ajax({
url:'{{ path('map.filter', {city:cityUriIdentity}) }}',
type: \"POST\",
dataType: \"json\",
cache: false,
data: {
\"form\": JSON.stringify(data),
\"mapContext\": mapContext,
\"scale\": myMap.getZoom(),
},
async: true,
}).then(getDetailsData).then(points => {
updateMap(points);
mapStatus.textContent = 'Анкеты: ' + points.profiles.length + '. Салоны: ' + points.saloons.length + '.';
}).catch(showError).always(() => setLoading(false));
}
function checkArrayIsInFormObject(name, formObject) {
if(false == formObject.hasOwnProperty(name))
formObject[name] = [];
}
function checkObjectIsInFormObject(name, formObject) {
if(false == formObject.hasOwnProperty(name))
formObject[name] = {};
}
function getDetailsData(data) {
const profilesRawData = data.profiles || [];
const saloonsRawData = data.saloons || [];
const profilesAllId = profilesRawData.map(_data => _data[0]).flat();
const saloonsAllId = saloonsRawData.map(_data => _data[0]).flat();
const profileArray = Array.isArray(profilesAllId) ? profilesAllId : [];
const saloonIdArray = Array.isArray(saloonsAllId) ? saloonsAllId : [];
const requestBody = {};
requestBody.profiles = profileArray;
requestBody.saloons = saloonIdArray;
return fetch('{{ path('map.detail', {city:cityUriIdentity}) }}', {
method: \"POST\",
cache: 'no-store',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
},
body: new URLSearchParams(requestBody).toString()
})
.then(response => {
if (!response.ok) {
throw new Error('Cannot load map details');
}
return response.json();
});
}
function updateMap(points) {
clusterer.removeAll();
if (!points || (points.profiles.length == 0 && points.saloons.length == 0)) {
myMap.setCenter([cityLatitude, cityLongitude], 9);
return;
}
const mergedPoints = [...points.profiles, ...points.saloons];
var getImgUrl = function(path, imgType) {
if(path[0] == '/')
return path;
console.log(imgType)
console.log(photoPath)
console.log(thumbPath)
var assetPackagePath = '';
if(imgType == 'avatar')
assetPackagePath = avatarPath;
else if(imgType == 'photo')
assetPackagePath = photoPath; // /media/profiles/vp/rd/vprdP4ShlKUpkOB.jpg
else if(imgType == 'thumb')
assetPackagePath = thumbPath; // /media/saloons/thumb///.jpg
return `\${assetPackagePath}\${path.slice(0, 2).toLowerCase()}/\${path.slice(2, 4).toLowerCase()}/\${path}.jpg`;
};
var getPointData = function (point) {
const isProfile = point[0] == 1;
const isSaloon = point[0] == 2;
let url = '';
const uri = point[3];
if(isProfile) {
url = RoutingDecorator.generate(
'profile_preview.page',
multipleCities ? {city: cityUriIdentity, profile: uri} : {profile: uri}
);
} else if(isSaloon) {
url = RoutingDecorator.generate(
'saloon_preview.page',
multipleCities ? {city: cityUriIdentity, saloon: uri} : {saloon: uri}
);
}
var processProfileShowsUrl = '{{ path('map.increment_profile_shows', multipleCities ? {city:cityUriIdentity} : {}) }}';
return {
balloonContentHeader: '',
balloonContentBody: '<p><img src=\"' + getImgUrl(point[5], isProfile ? 'avatar' : 'thumb') + '\" width=\"100\" /></p>' + '<font size=3><b><a target=\"_blank\" href=\"' + url + '\">Профиль</a></b></font>'
+ '<img style=\"display:none;\" width=\"0\" height=\"0\" src=\"' + processProfileShowsUrl + '?id=' + (isProfile ? point[9] : null)+'\" />', //не убирать, функционально важно
balloonContentFooter: '<font size=1>' + point[8] + ',' + point[9] + ',' + point[10] + '</strong>',
clusterCaption: '<strong>' + (isSaloon ? 'Салон ' : '') + point[4] + '</strong>'
};
};
var getPointOptions = function (index, type) {
return {
preset: type == 'profile' ? 'islands#violetIcon' : 'islands#redIcon'
};
};
var geoObjects = [];
for(var i = 0, len = mergedPoints.length; i < len; i++) {
const _point = mergedPoints[i];
geoObjects[i] = new ymaps.Placemark([_point[1], _point[2]], getPointData(_point), getPointOptions(i, _point[0] == 1));
}
//В кластеризатор можно добавить javascript-массив меток (не геоколлекцию) или одну метку.
clusterer.add(geoObjects);
myMap.geoObjects.add(clusterer);
// Спозиционируем карту так, чтобы на ней были видны все объекты.
if (mergedPoints.length === 1) {
myMap.setCenter([mergedPoints[0][1], mergedPoints[0][2]], 14);
} else {
myMap.setBounds(clusterer.getBounds(), {
checkZoomRange: true,
zoomMargin: 40
}).then(() => {
if (myMap.getZoom() > 14) {
myMap.setZoom(14);
}
});
}
}
});
})();
</script>
{% endblock %}
", "Map/page.html.twig", "/app/templates/Map/page.html.twig");
}
}