NikMaster777
@NikMaster777

Как передать метку на карту по координатам из админки?

Сделал страницу настроек в адмике Wordpress.
add_action( 'admin_menu', 'filter_map_menu_page', 25 );

function filter_map_menu_page() {
    add_menu_page(
        'Настройки карты', // тайтл страницы
        'Настройки карты', // текст ссылки в меню
        'manage_options', // права пользователя, необходимые для доступа к странице
        'true_filter', // ярлык страницы
        'true_filter_map_callback', // функция, которая выводит содержимое страницы
        'dashicons-images-alt2', // иконка, в данном случае из Dashicons
        4.3 // позиция в меню
    );
}

// Регистрация настроек
add_action( 'admin_init', 'true_filter_settings_init' );

function true_filter_settings_init() {
    register_setting( 'true_filter_settings', 'latitude_option' );
    register_setting( 'true_filter_settings', 'longitude_option' );

    add_settings_section( 'true_filter_section', '', 'true_filter_section_callback', 'true_filter' );

    add_settings_field( 'latitude_field', 'Широта', 'latitude_field_callback', 'true_filter', 'true_filter_section' );
    add_settings_field( 'longitude_field', 'Долгота', 'longitude_field_callback', 'true_filter', 'true_filter_section' );
}

function true_filter_section_callback() {
    // echo '<p>Описание секции</p>';
}

function latitude_field_callback() {
    $latitude = get_option( 'latitude_option' );
    echo '<input type="text" name="latitude_option" value="' . esc_attr( $latitude ) . '" />';
}

function longitude_field_callback() {
    $longitude = get_option( 'longitude_option' );
    echo '<input type="text" name="longitude_option" value="' . esc_attr( $longitude ) . '" />';
}

function true_filter_map_callback() {
    echo '<div class="wrap">
	<h1>' . get_admin_page_title() . '</h1>
	<form method="post" action="options.php">';

    settings_fields( 'true_filter_settings' ); // название настроек
    do_settings_sections( 'true_filter' ); // ярлык страницы, не более
    submit_button(); // функция для вывода кнопки сохранения

    echo '</form>';

}

// Добавляем уведомление при сохранении настроек
add_action( 'admin_notices', 'true_filter_settings_notice' );

function true_filter_settings_notice() {
    settings_errors();
}


Как передать метку на карту из широты и долготы указанных в этих настройках?
  • Вопрос задан
  • 78 просмотров
Пригласить эксперта
Ответы на вопрос 1
artzolin
@artzolin Куратор тега WordPress
php, WordPress разработка сайтов artzolin.ru
Тоже решал подобную проблему, в итоге решил собирать весь скрипт на php. Сначала собираю обычный массив, как в документации object_manager

$mask         = array();
$mask['type'] = 'FeatureCollection';

foreach ( $resorts as $key => $resort ) {

	$geo_point = get_post_meta( $resort->ID, '_geo_location', true );
	$geo_point = explode( ',', $geo_point );

	// Собираем php массив для карты, который энкодим в json формат
	$mask['features'][] = array(
		'type'       => 'Feature',
		'id'         => $key,
		'geometry'   => array (
			'type'        => 'Point',
			'coordinates' => [(float) trim($geo_point[0]), (float) trim($geo_point[1])],
		),
		'properties' => array (
			'balloonContentBody' => '<strong class="balloon-title"><a class="link" href="' . esc_url( get_the_permalink( $resort->ID ) ) . '" target="_blank">' . $resort->post_title . '</a></strong>',
			'clusterCaption'     => '<strong>' . $resort->post_title . '</strong>',
			'hintContent'        => '<strong>' . $resort->post_title . '</strong>'
		)
	);
}


С помощью json_encode() и wp_add_inline_script() вставляю все во фронт

$frontend_scripts = "<script type='text/javascript'>

	jQuery(function($){

		ymaps.ready(init);

		function init () {
			var map = new ymaps.Map('ya-map', {
					center: [55.76, 37.64],
					zoom: 4,
					controls: ['geolocationControl' ,'zoomControl'],
				}, {
					avoidFractionalZoom: false,
				});
				
			map.behaviors.disable(\"scrollZoom\");

			var objectManager = new ymaps.ObjectManager({
				clusterize: true,
				gridSize: 32,
				clusterDisableClickZoom: true
			});

			objectManager.objects.options.set( 'preset', 'islands#greenCircleDotIcon' );
			objectManager.clusters.options.set( 'preset', 'islands#greenClusterIcons' );

			map.geoObjects.add(objectManager);

			var pointLabels = " . json_encode( $mask ) . ";
			objectManager.add(pointLabels);

			// эта костыльная хуйня центрирует карту и делает автозум, чтобы попали все точки
			var geoObjects = ymaps.geoQuery(pointLabels)
				.applyBoundsToMap(map, {
					checkZoomRange: true
				});

		}

	});

</script>";

wp_add_inline_script( 'main', minify_js( $frontend_scripts ) );
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы