Skip to content

Instantly share code, notes, and snippets.

@kisildev
Created February 17, 2019 10:56
Show Gist options
  • Save kisildev/41b89e36d060a53a81fa317ac8d684f7 to your computer and use it in GitHub Desktop.
Save kisildev/41b89e36d060a53a81fa317ac8d684f7 to your computer and use it in GitHub Desktop.
ACF Google Map
<?php
// Load scripts and styles
function add_scripts_and_styles() {
if ( ! is_admin() ) {
// For styles
wp_enqueue_style( 'main-style', get_template_directory_uri() . '/style.css', null, null );
// For scripts (js)
wp_enqueue_script('jquery');
wp_enqueue_script( 'main-js', get_template_directory_uri() . '/js/main.js', null, null, true );
// Map
wp_enqueue_script( 'map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDGM14LfxXXL09Xek-NibRhRTahzwQ3NSM', null, null, true );
}
}
add_action( 'wp_enqueue_scripts', 'add_scripts_and_styles' );
// ACF Map
function my_acf_init() {
acf_update_setting('google_api_key', 'AIzaSyDGM14LfxXXL09Xek-NibRhRTahzwQ3NSM');
}
add_action('acf/init', 'my_acf_init');
.acf-map {
width: 100%;
height: 400px;
}
/* fixes potential theme css conflict */
.acf-map img {
max-width: inherit !important;
}
(function($) {
/*
* new_map
*
* This function will render a Google Map onto the selected jQuery element
*
* @type function
* @date 8/11/2013
* @since 4.3.0
*
* @param $el (jQuery element)
* @return n/a
*/
function new_map( $el ) {
// var
var $markers = $el.find('.marker');
// vars
var args = {
zoom : 16,
center : new google.maps.LatLng(0, 0),
mapTypeId : google.maps.MapTypeId.ROADMAP,
styles: [{
"featureType":"landscape",
"elementType":"all","stylers":
[{"hue":"#6600ff"},
{"saturation":-11}]
},
{
"featureType":"poi",
"elementType":"all",
"stylers":[{"saturation":-78},
{"hue":"#6600ff"},{"lightness":-47},
{"visibility":"off"}]},
{"featureType":"road","elementType":"all","stylers":[{"hue":"#5e00ff"},{"saturation":-79}]},
{"featureType":"road.local","elementType":"all","stylers":[{"lightness":30},{"weight":1.3}]},
{"featureType":"transit","elementType":"all","stylers":[{"visibility":"simplified"},
{"hue":"#5e00ff"},
{"saturation":-16}]},
{"featureType":"transit.line","elementType":"all","stylers":[{"saturation":-72}]},
{"featureType":"water","elementType":"all","stylers":[{"saturation":-65},{"hue":"#1900ff"},{"lightness":8}]}]
};
// create map
var map = new google.maps.Map( $el[0], args);
// add a markers reference
map.markers = [];
// add markers
$markers.each(function(){
add_marker( $(this), map );
});
// center map
center_map( map );
// return
return map;
}
/*
* add_marker
*
* This function will add a marker to the selected Google Map
*
* @type function
* @date 8/11/2013
* @since 4.3.0
*
* @param $marker (jQuery element)
* @param map (Google Map object)
* @return n/a
*/
function add_marker( $marker, map ) {
// var
var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
// Add 1
var markerImg = $marker.attr('data-marker');
// create marker
var marker = new google.maps.Marker({
position : latlng,
map : map,
// Add 2
icon: markerImg
});
// add to array
map.markers.push( marker );
// if marker contains HTML, add it to an infoWindow
if( $marker.html() )
{
// create info window
var infowindow = new google.maps.InfoWindow({
content : $marker.html()
});
// show info window when marker is clicked
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
/*
* center_map
*
* This function will center the map, showing all markers attached to this map
*
* @type function
* @date 8/11/2013
* @since 4.3.0
*
* @param map (Google Map object)
* @return n/a
*/
function center_map( map ) {
// vars
var bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
// only 1 marker?
if( map.markers.length == 1 )
{
// set center of map
map.setCenter( bounds.getCenter() );
map.setZoom( 16 );
}
else
{
// fit to bounds
map.fitBounds( bounds );
}
}
/*
* document ready
*
* This function will render each map when the document is ready (page has loaded)
*
* @type function
* @date 8/11/2013
* @since 5.0.0
*
* @param n/a
* @return n/a
*/
// global var
var map = null;
$(document).ready(function(){
$('.acf-map').each(function(){
// create map
map = new_map( $(this) );
});
});
})(jQuery);
<!-- Map -->
<?php if( $location = get_field('location', 'options') ): ?>
<div class="acf-map">
<div class="marker" data-marker="<?php echo get_stylesheet_directory_uri().'/images/marker.svg'; ?>" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>"></div>
</div>
<?php endif; ?>
@kisildev
Copy link
Author

ACF Google Map

  1. Создаем ACF Google Map поле в админке и выбираем точку на карте.
  2. Вставляем код с map.php - не забываем прописать в get_field() нужный слаг, чтобы получить нашу карту.

Обратите внимание на data-marker="<?php echo get_stylesheet_directory_uri().'/images/marker.svg'; ?>" - сюда вы можете вывести картинку с помощью ACF для вашего маркера (например, data-marker="<?php echo $marker_img; ?> ).

  1. Регистрируем наш Google Api Key в functions.php
    • в функции подключения скриптов - wp_enqueue_script( 'map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDGM14LfxXXL09Xek-NibRhRTahzwQ3NSM', null, null, true );

    • в произвольном месте файла:

     function my_acf_init() {
        acf_update_setting('google_api_key', 'AIzaSyDGM14LfxXXL09Xek-NibRhRTahzwQ3NSM');
     }
     add_action('acf/init', 'my_acf_init');
  1. Вставляем js код.

Обратите внимание, в конце js кода указывается класс нашей карты, он должен совпадать с тем что в верстке

$(document).ready(function(){
    $('.acf-map').each(function(){
        // create map
        map = new_map( $(this) );
    });
});
  1. Для стилизации карты используем сервис - https://snazzymaps.com

  2. Задаем карте стили.

@dexit
Copy link

dexit commented Feb 8, 2022

Nice +1

Очень помогло, спасибо !

Below was for Elementor
Google Maps ACF field in ACF PRO now has all data, so i updated the html like so to get the real marker< obvioiusly we can pull in more data by adjusting the JS file provided above, and get Zoom level and Marker dimensions even html for the baloon modal, but below is just marker update:

// Load scripts and styles
function add_scripts_and_styles() {
	if ( ! is_admin() ) {
		// For styles
		wp_enqueue_style( 'maped-style', get_template_directory_uri() . '/css/maped.css', null, null );
		// below 2 loaded by elementor
		//wp_enqueue_script('jquery');
		//wp_enqueue_script( 'main-js', get_template_directory_uri() . '/js/maped.js', array( 'jquery' ), false, true );
		// Map
		if('new_homes' == get_post_type()) {
		wp_enqueue_script( 'map', 'https://maps.googleapis.com/maps/api/js?key=GMAPS-API-KEY', null, null, true );
			}
	}
}
add_action( 'wp_enqueue_scripts', 'add_scripts_and_styles' );

// Add Shortcode
function loadcustommap() {

	if( $location = get_field('map') ){
		echo '<div class="acf-map">';
		echo '<div class="marker" data-marker="'. $location["marker"]["url"] .'" data-lat="'. $location["lat"] .'" data-lng="'. $location["lng"] .'"></div>';
		echo '</div>';
	}

}
add_shortcode( 'mapload', 'loadcustommap' ); 

Also a pretty good reference
https://yogeshchauhan.com/how-to-add-google-map-in-wordpress-using-acf/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment