Created
March 15, 2018 14:07
-
-
Save EvilGoTa/dda0164cb7aca1bd42ec434dd3c661cb to your computer and use it in GitHub Desktop.
ymaps objectCollection, cluster, click events and more
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function init(){ | |
ymaps.geolocation.get({ | |
// Зададим способ определения геолокации | |
// на основе ip пользователя. | |
provider: 'yandex', | |
// Включим автоматическое геокодирование результата. | |
autoReverseGeocode: true | |
}).then(function (result) { | |
// Выведем результат геокодирования. | |
console.log('--> Выведем результат геокодирования'); | |
console.log(result.geoObjects.get(0).properties.get('metaDataProperty')); | |
}); | |
console.log('--> map initiating...'); | |
$('#map').html(''); | |
myMap = new ymaps.Map ("map", { | |
center: client_coords, | |
zoom: 9, | |
maxZoom: 9 | |
}); | |
var icon = '/wa-data/public/site/themes/heatstyle/img/delivery1.png' | |
var msg = 'Моё местоположение'; | |
var msg2 = 'Моё местоположение'; | |
if ($('.block_courier').length > 0) { | |
icon = '/wa-data/public/site/themes/heatstyle/img/delivery2.png'; | |
msg = 'Моё местоположение - Курьерская доставка'; | |
msg2 = 'Достака курьером на Ваш адрес'; | |
} | |
myPlacemark = new ymaps.Placemark([client_coords[1],client_coords[0]], { | |
hintContent: msg, | |
balloonContent: msg2, | |
wa_id: 'courier', | |
}, { | |
iconLayout: 'default#image', | |
iconImageHref: icon, | |
iconImageSize: [50, 50], | |
iconImageOffset: [-25, -0], | |
hideIconOnBalloonOpen: false, | |
}); | |
myMap.geoObjects.add(myPlacemark); | |
clusterer = new ymaps.Clusterer({ | |
preset: 'islands#invertedblueClusterIcons', | |
groupByCoordinates: false, | |
clusterDisableClickZoom: true, | |
clusterHideIconOnBalloonOpen: false, | |
geoObjectHideIconOnBalloonOpen: false | |
}); | |
geoObjects = []; | |
var i = 0; | |
points_json = { | |
'type': "FeatureCollection", | |
"features": [], | |
}; | |
console.log('--> points processing...'); | |
$('.point__block.ym').each(function() { | |
var lat = $(this).attr('data-lat'); | |
var long = $(this).attr('data-long'); | |
var name = $(this).attr('data-method-name'); | |
var method = $(this).attr('data-method'); | |
var address = $(this).find('h3').text(); | |
var price = $(this).find('p').text(); | |
var id = $(this).attr('data-point-id'); | |
if (!id) { | |
return; | |
} | |
var images = { | |
6: '/wa-data/public/shop/deliv/1/1.jpg', | |
7: '/wa-data/public/shop/deliv/3/3.jpg', | |
8: '/wa-data/public/shop/deliv/4/4.png', | |
9: '/wa-data/public/shop/deliv/5/5.jpeg', | |
11: '/wa-data/public/shop/deliv/7/7.jpeg', | |
12: '/wa-data/public/shop/deliv/8/8.jpg', | |
13: '/wa-data/public/shop/deliv/9/9.jpg', | |
} | |
points_json.features.push({ | |
'type': 'Feature', | |
'id': i, | |
'geometry': { | |
'type': 'Point', | |
"coordinates": [lat, long] | |
}, | |
'properties': { | |
balloonContent: ["<img style='width: 100px; height: auto' src='"+images[method]+"'>", address, price, '<a href="#" class="set_delivery">выбрать</a>'].join('<br>'), | |
clusterCaption: name, | |
hintContent: ["<img style='width: 100px; height: auto' src='"+images[method]+"'> ", address, price].join('<br>'), | |
wa_id: id, | |
}, | |
'options': { | |
preset: 'islands#blueIcon' | |
} | |
}); | |
i++; | |
}); | |
console.log('--> points processing done'); | |
objectManager = new ymaps.ObjectManager({ | |
// Чтобы метки начали кластеризоваться, выставляем опцию. | |
clusterize: true, | |
// ObjectManager принимает те же опции, что и кластеризатор. | |
gridSize: 80, | |
clusterDisableClickZoom: true | |
}); | |
clusterer.add(geoObjects); | |
// установим тот способ, кторый определился как самы йблизкий | |
function setMethod(wa_id) { | |
var target_method_point = $('.point__block[data-point-id='+wa_id+']:first'); | |
var method = target_method_point.attr('data-method'); | |
if (wa_id == 'courier') { | |
console.log(target_method_point); | |
console.log(method); | |
} | |
if ($('input#company_'+method).length) { | |
$('input#company_'+method).trigger('click'); | |
} else { | |
$('input#shipping_'+method).trigger('click'); | |
} | |
target_method_point.trigger('click'); | |
setTimeout(function() { | |
$('.points_data').scrollTop( | |
$('.point__block.active').offset().top - $('.points_data').offset().top + $('.points_data').scrollTop() | |
); | |
}, 500); | |
} | |
$('.point__block').click(function(e) { | |
console.log(e); | |
if (e.originalEvent) { | |
var selected_point = window.qPoints.search('properties.wa_id='+$(this).attr('data-point-id')); | |
console.log(selected_point.get(0)); | |
myMap.setCenter(selected_point.get(0).geometry.getCoordinates()); | |
} | |
}) | |
window.qPoints = ymaps.geoQuery(geoObjects); | |
var closestObject = qPoints.getClosestTo(myPlacemark); | |
console.log(closestObject); | |
// myMap.geoObjects.add(clusterer); | |
myMap.geoObjects.add(objectManager); | |
objectManager.add(points_json); | |
// myMap.geoObjects.add(geoObjects); | |
myMap.geoObjects.events.add(['click'], function(e) { | |
console.log('map click'); | |
if (e.get('target').properties) { | |
console.log(e.get('target').properties.get('wa_id')); | |
setMethod(e.get('target').properties.get('wa_id')); | |
if (window.ymaps_delivery_red_object) { | |
objectManager.objects.setObjectOptions(window.ymaps_delivery_red_object, { | |
preset: 'islands#blueIcon' | |
}); | |
} | |
} | |
// setMethod(e.get('target').properties.get('wa_id')); | |
// console.log(e.get('target'), e.target, e); | |
}); | |
function onObjectClick (e) { | |
// objectId – идентификатор объекта, на котором произошло событие. | |
var objectId = e.get('objectId'), | |
object = objectManager.objects.getById(objectId); | |
// Выведем информацию об объекте. | |
console.log('Тип объекта: ' + object.geometry.type); | |
console.log('Координаты объекта: ' + object.geometry.coordinates); | |
console.log(object.properties.wa_id); | |
setMethod(object.properties.wa_id); | |
} | |
// Подписываемся на событие клика по объекту. | |
objectManager.objects.events.add(['click'], function (e) { | |
// objectId – идентификатор объекта, на котором произошло событие. | |
var objectId = e.get('objectId'), | |
object = objectManager.objects.getById(objectId); | |
window.ymaps_delivery_id = object.properties.wa_id; | |
window.ymaps_delivery_current_object = objectId; | |
// обновляем ид выбранного класера, т.к. выбрали точку и кластер красить не нужно | |
window.ymaps_delivery_current_cluster = null; | |
}); | |
objectManager.clusters.events.add(['click'], function(e) { | |
var objectId = e.get('objectId'), | |
object = objectManager.clusters.getById(objectId); | |
window.ymaps_delivery_current_cluster = objectId; | |
var state = objectManager.clusters.state.get('activeObject'); | |
if (typeof state == 'object') { | |
window.ymaps_delivery_id = state.properties.wa_id; | |
window.ymaps_delivery_current_object = objectId; | |
} | |
}); | |
var monitor = new ymaps.Monitor(objectManager.clusters.state); | |
monitor.add('activeObject', function(newValue) { | |
console.log('cluster click'); | |
console.log(newValue); | |
window.ymaps_delivery_id = newValue.properties.wa_id; | |
window.ymaps_delivery_current_object = newValue.id; | |
}); | |
$('#map').on('click', '.set_delivery', function() { | |
setMethod(window.ymaps_delivery_id); | |
window.ymaps_scroll_to_payment = true; | |
// если были окрашены точки\кластеры ранее, красим их обратно | |
if (window.ymaps_delivery_prev_object) { | |
console.log('красим старую точку'); | |
objectManager.objects.setObjectOptions(window.ymaps_delivery_prev_object, { | |
preset: 'islands#blueIcon' | |
}); | |
} | |
if (window.ymaps_delivery_prev_cluster) { | |
console.log('красим старый кластер'); | |
objectManager.clusters.setClusterOptions(window.ymaps_delivery_prev_cluster, { | |
preset: 'islands#blueClusterIcons' | |
}); | |
} | |
// красим текущую точку | |
if (window.ymaps_delivery_current_object) { | |
console.log('красим новую точку'); | |
objectManager.objects.setObjectOptions(window.ymaps_delivery_current_object, { | |
preset: 'islands#redIcon' | |
}); | |
window.ymaps_delivery_prev_object = window.ymaps_delivery_current_object; | |
} | |
// красим текущий кластер | |
if (window.ymaps_delivery_current_cluster) { | |
console.log('красим новый кластер'); | |
objectManager.clusters.setClusterOptions(window.ymaps_delivery_current_cluster, { | |
preset: 'islands#redClusterIcons' | |
}); | |
window.ymaps_delivery_prev_cluster = window.ymaps_delivery_current_cluster; | |
} | |
myMap.balloon.close(); | |
return false; | |
}) | |
// myMap.setBounds([myPlacemark.geometry.getCoordinates(), closestObject.geometry.getCoordinates()], { | |
// zoomMargin: 50 | |
// }); | |
myMap.setCenter(myPlacemark.geometry.getCoordinates()); | |
myMap.setZoom(14); | |
myPlacemark.balloon.open(); | |
// скролим окно до карты | |
if (window.scrollToMap) { | |
var scrollTo = $('.checkout-step.step-shipping').offset().top-120; | |
console.log('scroll to '+scrollTo); | |
var body = $("html, body"); | |
body.stop().animate({ | |
scrollTop:scrollTo | |
}, 500, 'swing'); | |
} else { | |
window.scrollToMap = 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment