LeafletJS

This commit is contained in:
Krivchikov Dmitry 2014-06-19 16:17:34 +04:00
parent 8c76fd01d8
commit 4b2b77c0a6
4 changed files with 139 additions and 127 deletions

View File

@ -10,10 +10,11 @@ class IndexController extends Controller
{ {
self::addScript('/js/jquery-2.1.0.min.js'); self::addScript('/js/jquery-2.1.0.min.js');
self::addScript('/js/jquery-ui-1.10.4.custom.min.js'); self::addScript('/js/jquery-ui-1.10.4.custom.min.js');
self::addScript('http://api-maps.yandex.ru/2.0-stable/?load=package.full&lang=ru-RU&mode=release'); self::addScript('http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js');
self::addScript('/js/main.js?ver='.App::getConfig('version')); self::addScript('/js/main.js?ver='.App::getConfig('version'));
self::addScript('/js/bootstrap.min.js'); self::addScript('/js/bootstrap.min.js');
self::addStyle('/css/style.css?ver='.App::getConfig('version')); self::addStyle('/css/style.css?ver='.App::getConfig('version'));
self::addStyle('http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css');
self::addStyle('/css/bootstrap.min.css'); self::addStyle('/css/bootstrap.min.css');
self::addStyle('/css/bootstrap-theme.min.css'); self::addStyle('/css/bootstrap-theme.min.css');

View File

@ -21,6 +21,7 @@ class JsonController extends Controller
$result[$point['id']]['name'] = $point['name']; $result[$point['id']]['name'] = $point['name'];
$result[$point['id']]['lat'] = $point['lat']; $result[$point['id']]['lat'] = $point['lat'];
$result[$point['id']]['lng'] = $point['lng']; $result[$point['id']]['lng'] = $point['lng'];
$result[$point['id']]['categoryId'] = $point['categoryId'];
$result[$point['id']]['categoryIcon'] = $categories[$point['categoryId']]['icon']; $result[$point['id']]['categoryIcon'] = $categories[$point['categoryId']]['icon'];
} }

View File

@ -22,6 +22,7 @@
<?php endforeach; ?> <?php endforeach; ?>
</script> </script>
<?php endif; ?> <?php endif; ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
</head> </head>
<body> <body>

View File

@ -35,9 +35,9 @@ function resetStatus()
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
ymaps.ready(init); $(document).ready(function(){init()});
var myMap; var myMap;
var categories; var categories = Array();
var points = Array(); var points = Array();
var pointsSources = Array(); var pointsSources = Array();
var search; var search;
@ -57,107 +57,121 @@ function getURLParameter(name) {
* @returns true * @returns true
*/ */
function init() { function init() {
questLayer = function () { myMap = L.map('map').setView([51.505, -0.09], 13);
return new ymaps.Layer( L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
'http://otile1.mqcdn.com/tiles/1.0.0/osm/%z/%x/%y.png', {projection: ymaps.projection.sphericalMercator}); 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
ymaps.layer.storage.add('quest#layer', questLayer); }).addTo(myMap);
ymaps.mapType.storage.add('quest#type', new ymaps.MapType('MapQuest', ['quest#layer']));
osmLayer = function () { //
return new ymaps.Layer( // questLayer = function () {
'http://c.tile.openstreetmap.org/%z/%x/%y.png', {projection: ymaps.projection.sphericalMercator}); // return new ymaps.Layer(
}; // 'http://otile1.mqcdn.com/tiles/1.0.0/osm/%z/%x/%y.png', {projection: ymaps.projection.sphericalMercator});
ymaps.layer.storage.add('osm#layer', osmLayer); // };
ymaps.mapType.storage.add('osm#type', new ymaps.MapType('OpenStreetMap', ['osm#layer'])); // ymaps.layer.storage.add('quest#layer', questLayer);
// ymaps.mapType.storage.add('quest#type', new ymaps.MapType('MapQuest', ['quest#layer']));
googleLayer = function () { //
return new ymaps.Layer('http://mt0.google.com/vt/lyrs=s@176000000&hl=ru&%c', {projection: ymaps.projection.sphericalMercator,tileTransparent: true}); // osmLayer = function () {
} // return new ymaps.Layer(
ymaps.layer.storage.add('google#layer', googleLayer); // 'http://c.tile.openstreetmap.org/%z/%x/%y.png', {projection: ymaps.projection.sphericalMercator});
ymaps.mapType.storage.add('google#type', new ymaps.MapType('Google Maps', ['google#layer'])); // };
// ymaps.layer.storage.add('osm#layer', osmLayer);
myMap = new ymaps.Map("map", { // ymaps.mapType.storage.add('osm#type', new ymaps.MapType('OpenStreetMap', ['osm#layer']));
center: [ymaps.geolocation.latitude, ymaps.geolocation.longitude], //
zoom: 12, // googleLayer = function () {
type:'quest#type', // return new ymaps.Layer('http://mt0.google.com/vt/lyrs=s@176000000&hl=ru&%c', {projection: ymaps.projection.sphericalMercator,tileTransparent: true});
behaviors: ['default', 'scrollZoom'] // }
}); // ymaps.layer.storage.add('google#layer', googleLayer);
// ymaps.mapType.storage.add('google#type', new ymaps.MapType('Google Maps', ['google#layer']));
myMap.controls.add('mapTools'); //
myMap.controls.add('smallZoomControl'); // myMap = new ymaps.Map("map", {
myMap.controls.add('scaleLine'); // center: [ymaps.geolocation.latitude, ymaps.geolocation.longitude],
// zoom: 12,
typeSelector = new ymaps.control.TypeSelector(); // type:'quest#type',
typeSelector.addMapType('quest#type', 0); // behaviors: ['default', 'scrollZoom']
typeSelector.addMapType('google#type', 1); // });
typeSelector.addMapType('yandex#publicMap', 2); //
typeSelector.addMapType('osm#type', 3); // myMap.controls.add('mapTools');
myMap.controls.add(typeSelector); // myMap.controls.add('smallZoomControl');
myMap.copyrights.add('Участники <a href="http://www.openstreetmap.org/copyright" target="blank">OpenStreetMap</a>'); // myMap.controls.add('scaleLine');
myMap.copyrights.add('Tiles courtesy of <a href="http://www.mapquest.com/" target="blank">MapQuest</a>'); //
// typeSelector = new ymaps.control.TypeSelector();
// typeSelector.addMapType('quest#type', 0);
// typeSelector.addMapType('google#type', 1);
// typeSelector.addMapType('yandex#publicMap', 2);
// typeSelector.addMapType('osm#type', 3);
// myMap.controls.add(typeSelector);
// myMap.copyrights.add('Участники <a href="http://www.openstreetmap.org/copyright" target="blank">OpenStreetMap</a>');
// myMap.copyrights.add('Tiles courtesy of <a href="http://www.mapquest.com/" target="blank">MapQuest</a>');
initCategories() initCategories()
getPoints(); // getPoints();
myMap.events.add('click', function(e) { // myMap.events.add('click', function(e) {
if (!myMap.balloon.isOpen()) { // if (!myMap.balloon.isOpen()) {
if (status == statusHunting) // if (status == statusHunting)
{ // {
coords = e.get('coordPosition'); // coords = e.get('coordPosition');
//
// $('#addPointId').remove();
// $('#addPointForm input').val('');
// $("#addPointCategoryId option" ).attr('selected', null);
// $('#addPointLat').val(coords[0].toPrecision(11));
// $('#addPointLng').val(coords[1].toPrecision(11));
//
// $('#myModalLabel').text('Добавление новой точки');
// $('#addPointModal').modal('show');
// } else if (status == statusReHunting)
// {
// resetStatus();
// coords = e.get('coordPosition');
//
// $('#addPointLat').val(coords[0].toPrecision(11));
// $('#addPointLng').val(coords[1].toPrecision(11));
//
// $('#myModalLabel').text('Редактирование точки');
// $('#addPointModal').modal('show');
// }
// }
// else {
// myMap.balloon.close();
// }
// });
//
// myMap.events.add('boundschange', function(e) {
// 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'));
// }
// });
//
// points.im = new ymaps.Placemark(
// [ymaps.geolocation.latitude, ymaps.geolocation.longitude],
// {
// balloonContentHeader: 'Вы здесь',
// hintContent: 'Ваше местоположение',
// balloonContent:
// '<button type="button" class="btn btn-default btn-xs" onclick="addToRoute(\'im\')">' +
// '<span class="glyphicon glyphicon-plus"></span> Добавить в маршрут' +
// '</button>'
// },
// {
// iconImageHref: '/ico/man.png',
// iconImageSize: [32, 37],
// iconImageOffset: [-16, -33],
// }
// );
// myMap.geoObjects.add(points.im);
//
// $("#wayPoints").sortable();
// $("#wayPoints").disableSelection();
$('#addPointId').remove(); myMap.on('moveend', function(e) {
$('#addPointForm input').val(''); if (!myMap._popup && $('#routeWindow').css('display') == 'none')
$("#addPointCategoryId option" ).attr('selected', null); {
$('#addPointLat').val(coords[0].toPrecision(11)); history.pushState({}, document.title, "/?lat=" + myMap.getCenter().lat + "&lng=" + myMap.getCenter().lng + "&zoom=" + myMap.getZoom());
$('#addPointLng').val(coords[1].toPrecision(11)); }
});
$('#myModalLabel').text('Добавление новой точки');
$('#addPointModal').modal('show');
} else if (status == statusReHunting)
{
resetStatus();
coords = e.get('coordPosition');
$('#addPointLat').val(coords[0].toPrecision(11));
$('#addPointLng').val(coords[1].toPrecision(11));
$('#myModalLabel').text('Редактирование точки');
$('#addPointModal').modal('show');
}
}
else {
myMap.balloon.close();
}
});
myMap.events.add('boundschange', function(e) {
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'));
}
});
points.im = new ymaps.Placemark(
[ymaps.geolocation.latitude, ymaps.geolocation.longitude],
{
balloonContentHeader: 'Вы здесь',
hintContent: 'Ваше местоположение',
balloonContent:
'<button type="button" class="btn btn-default btn-xs" onclick="addToRoute(\'im\')">' +
'<span class="glyphicon glyphicon-plus"></span> Добавить в маршрут' +
'</button>'
},
{
iconImageHref: '/ico/man.png',
iconImageSize: [32, 37],
iconImageOffset: [-16, -33],
}
);
myMap.geoObjects.add(points.im);
$("#wayPoints").sortable();
$("#wayPoints").disableSelection();
return true; return true;
} }
@ -170,22 +184,10 @@ function init() {
function constructPoint(data) function constructPoint(data)
{ {
id = data['id']; 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) { points[id] = L.marker(
showInfo(e.get('target').properties.get('id')); [data['lat'], data['lng']], {icon: categories[data['categoryId']], title: data['name'],id: id}
}); ).on('click', function(e){showInfo(e.target.options.id);});
return points[id]; return points[id];
} }
@ -200,7 +202,7 @@ function getPoints()
url: "/json/points/", url: "/json/points/",
success: function(data) { success: function(data) {
for (var k in data) { for (var k in data) {
myMap.geoObjects.add(constructPoint(data[k])); constructPoint(data[k]).addTo(myMap);
} }
if (getURLParameter('point') != 'null') if (getURLParameter('point') != 'null')
@ -212,7 +214,7 @@ function getPoints()
buildRoute(); buildRoute();
} else if ((getURLParameter('lat') != 'null') && (getURLParameter('lng') != 'null') && (getURLParameter('zoom') != 'null')) } else if ((getURLParameter('lat') != 'null') && (getURLParameter('lng') != 'null') && (getURLParameter('zoom') != 'null'))
{ {
myMap.setCenter([getURLParameter('lat'), getURLParameter('lng')], getURLParameter('zoom')); myMap.setView([getURLParameter('lat'), getURLParameter('lng')], getURLParameter('zoom'));
} }
} }
}); });
@ -227,9 +229,10 @@ function getPoints()
*/ */
function showInfo(id) function showInfo(id)
{ {
if (!(id in points) || points[id].properties.get('balloonContent') == undefined) marker = points[id];
if (!(id in points) || marker.options.description == undefined)
{ {
points[id].properties.set('balloonContent', 'Загрузка...'); marker.bindPopup("Загрузка...").openPopup();
$.ajax({ $.ajax({
url: "/json/point/id/" + id, url: "/json/point/id/" + id,
success: function(data) { success: function(data) {
@ -254,13 +257,9 @@ function showInfo(id)
description = description + ' <a href="' + data.source + '" target="blank">Подробнее...</a>'; description = description + ' <a href="' + data.source + '" target="blank">Подробнее...</a>';
description = description + '</div>'; description = description + '</div>';
points[id].properties.set('balloonContent', description);
point = getURLParameter('point'); marker.options.description = description;
if (point != null && id == point) marker.bindPopup(marker.options.description, {maxWidth: 500}).openPopup();
{
points[point].balloon.open();
}
} }
}); });
} }
@ -278,7 +277,17 @@ function initCategories()
$.ajax({ $.ajax({
url: "/json/categories/", url: "/json/categories/",
success: function(data) { success: function(data) {
categories = data; //categories = data;
for (var k in data) {
categories[data[k]['id']] = L.icon({
iconUrl: data[k]['icon'],
iconSize: [32, 37], // size of the icon
iconAnchor: [16, 37], // point of the icon which will correspond to marker's location
popupAnchor: [0, 1] // point from which the popup should open relative to the iconAnchor
});
}
getPoints();
} }
}); });