Answer the question
In order to leave comments, you need to log in
How to output data from JSON?
Good afternoon!
Tell me: on the Yandex map, display in the balloon "Title (clickable)", "page image" and "description" from the page (wordpress)
Click on the balloon, there is information with a picture and after clicking on the title (or the "more" link) the page opens .
just inserting the links of the rules everything works .. (following the example from Yandex) but I wanted to automate it so to speak .. type by page ID to open
One balloon = one page (construction object)
In the example below, as I understand it, there are ID and IDX they correspond to the link to page on the site (for example: in JSON ("properties":{"idx":"C2167","id":"2167","section":"16"
<script type="text/javascript">
var myMap;
var lines;
var multiRoute;
ymaps.ready(function () {
myMap = new ymaps.Map('shop_map', {
center: [55.434042, 37.521041],
controls: [],
zoom: 14
}, {
});
var MyBalloonLayout = ymaps.templateLayoutFactory.createClass(
'<div class="label__infoBlock popover">' +
'<div class="label__infoInner">' +
'$' +
'</div>' +
'<div class="labelFlag"></div>' +
'<div class="labelClose close"></div>' +
'</div>'
,{
/**
* Строит экземпляр макета на основе шаблона и добавляет его в родительский HTML-элемент.
* @see https://api.yandex.ru/maps/doc/jsapi/2.1/ref/reference/layout.templateBased.Base.xml#build
* @function
* @name build
*/
build: function () {
this.constructor.superclass.build.call(this);
this._$element = $('.popover', this.getParentElement());
this.applyElementOffset();
setTimeout(function(){
$(".labelText").mCustomScrollbar({
theme:"dark",
});
}, 2000);
this._$element.find('.close')
.on('click', $.proxy(this.onCloseClick, this));
},
/**
* Удаляет содержимое макета из DOM.
* @see https://api.yandex.ru/maps/doc/jsapi/2.1/ref/reference/layout.templateBased.Base.xml#clear
* @function
* @name clear
*/
clear: function () {
this._$element.find('.close')
.off('click');
this.constructor.superclass.clear.call(this);
},
/**
* Метод будет вызван системой шаблонов АПИ при изменении размеров вложенного макета.
* @see https://api.yandex.ru/maps/doc/jsapi/2.1/ref/reference/IBalloonLayout.xml#event-userclose
* @function
* @name onSublayoutSizeChange
*/
onSublayoutSizeChange: function () {
MyBalloonLayout.superclass.onSublayoutSizeChange.apply(this, arguments);
if(!this._isElement(this._$element)) {
return;
}
this.applyElementOffset();
this.events.fire('shapechange');
},
/**
* Сдвигаем балун, чтобы "хвостик" указывал на точку привязки.
* @see https://api.yandex.ru/maps/doc/jsapi/2.1/ref/reference/IBalloonLayout.xml#event-userclose
* @function
* @name applyElementOffset
*/
applyElementOffset: function () {
this._$element.css({
left: -(this._$element[0].offsetWidth / 2 - 110),
top: -(this._$element[0].offsetHeight + this._$element.find('.labelFlag')[0].offsetHeight)
});
console.log (this._$element[0].offsetHeight);
},
/**
* Закрывает балун при клике на крестик, кидая событие "userclose" на макете.
* @see https://api.yandex.ru/maps/doc/jsapi/2.1/ref/reference/IBalloonLayout.xml#event-userclose
* @function
* @name onCloseClick
*/
onCloseClick: function (e) {
e.preventDefault();
this.events.fire('userclose');
},
/**
* Используется для автопозиционирования (balloonAutoPan).
* @see https://api.yandex.ru/maps/doc/jsapi/2.1/ref/reference/ILayout.xml#getClientBounds
* @function
* @name getClientBounds
* @returns {Number[][]} Координаты левого верхнего и правого нижнего углов шаблона относительно точки привязки.
*/
getShape: function () {
if(!this._isElement(this._$element)) {
return MyBalloonLayout.superclass.getShape.call(this);
}
var position = this._$element.position();
return new ymaps.shape.Rectangle(new ymaps.geometry.pixel.Rectangle([
[position.left, position.top], [
position.left + this._$element[0].offsetWidth,
position.top + this._$element[0].offsetHeight + this._$element.find('.labelFlag')[0].offsetHeight
]
]));
},
/**
* Проверяем наличие элемента (в ИЕ и Опере его еще может не быть).
* @function
* @private
* @name _isElement
* @param {jQuery} [element] Элемент.
* @returns {Boolean} Флаг наличия.
*/
_isElement: function (element) {
return element && element[0] && element.find('.labelFlag')[0];
}
});
var MyBalloonContentLayout = ymaps.templateLayoutFactory.createClass( '$[properties.balloonContent]' );
ymaps.layout.storage.add('my#layout', MyBalloonLayout);
ymaps.layout.storage.add('my#baloonlayout', MyBalloonContentLayout);
jQuery.getJSON('/mapx/test.json', function (json) {
myMap.myObjects = ymaps.geoQuery(json).addToMap(myMap);
myMap.myObjects.each(function(pm) {
//console.log(pm.geometry.getCoordinates());
//pm.setOptions({'preset', 'islands#redIcon'});
//pm.options.set("visible", true);
//console.log(pm.properties.get("section"));
});
myMap.geoObjects.events.add('click', function (e) {
var object = e.get('target');
var idx = object.properties.get('id');
if(idx){
//object.properties.balloonContent = "yyyy";
//object.balloon.open();
object.properties.set(
'balloonContent',
'Загрузка ...'
);
for(var property in obj) {
alert(property + "=" + obj[property]);
}
$.ajax("/mapx/test.json", { name })
.done(function(data) {
object.properties.set(
'balloonContent',
data
);
});
}
//console.log ( object.geometry.getCoordinates() );
});
});
Answer the question
In order to leave comments, you need to log in
You need to collect the data of all objects in json format
$mask = array();
$mask['type'] = 'FeatureCollection';
foreach ( $variable as $key => $value ) {
$mask['features'][] = array(
"type" => 'Feature',
"id"=> $key,
"geometry" => array (
"type" => 'Point',
"coordinates" => [(float) $value->lat, (float) $value->long],
),
"properties" => array (
"balloonContentBody" => "<strong class='map-title'><a class='link' href='" . $value->post_link . "'>" . $value->post_title . "</a></strong>",
"balloonContentFooter" => "<a class='hidden' href='#'>Я был здесь!</a>",
"clusterCaption" => "<strong>" . $value->post_title . "</strong>",
"hintContent" => "<strong>" . $value->post_title . "</strong>"
)
);
}
json_encode( $mask )
pass to the handler as in this example https://yandex.ru/dev/maps/jsbox/2.1/object_manager/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question