ACF를 사용하여 사용자 정의 발언에 맵 표시 - WordPress

이것은 WordPress 사용자 정의 발언에 지도를 표시할 때의 비망록입니다.
  • 맞춤형 투고 유형: 점포 정보(shop)
  • 사용자 지정 필드: Map
  • (20221.02) 추가


    나는 지도를 표시하는 스크립트 (Googlemap.js-jQuery) 를pure JS로 고쳤다.

    발언 설정 사용자 정의


    참고 가치가 있는 보도.
    [WordPress] 플러그인 없이 사용자 정의 게시 형식에 사용자 정의 필드(텍스트 및 이미지)를 추가하는 방법
    register_post_type() - WordPress Developer Resources
    functions.php에 기술하다.
    function create_post_type() {
      register_post_type(
        'shops',
        array(
          'label' => '店舗情報',
          'public' => true,
          'has_archive' => true,
          'menu_position' => 3,
          'supports' => array(
            'title',
            'editor',
            'author',
            'thumbnail',
            'revisions'
          ),
          'show_in_rest' => true
        )
      );
    }
    add_action('init', 'create_post_type');
    

    ACF 설정


    Advanced Custom Fields 플러그인을 설치하고 활성화합니다.
    Advanced Custom Fields

    필드 그룹 편집


    필드 유형Googleマップ을 선택합니다.
    Edit Field Group
    투고 유형으로 선택店舗情報.
    投稿タイプ

    ACF에서 Google Maps를 사용하기 위한 준비


    참고 가치가 있는 보도.
    WordPress 기고 페이지에 Google Map을 표시하는 방법
    Field Types > Google Map - ACF Documentation

    스타일 설정

    style.css에서 설명합니다.
    .acf-map {
      width: 100%;
      height: 400px;
    }
    .acf-map img {
      max-width: inherit !important;
    }
    

    스크립트 만들기

    ACF의 템플릿을 직접 사용합니다.js/googlemap.js에서 설명합니다.
    (function( $ ) {
    
      /**
       * initMap
       *
       * Renders a Google Map onto the selected jQuery element
       *
       * @date    22/10/19
       * @since   5.8.6
       *
       * @param   jQuery $el The jQuery element.
       * @return  object The map instance.
       */
      function initMap( $el ) {
      
          // Find marker elements within map.
          var $markers = $el.find('.marker');
      
          // Create gerenic map.
          var mapArgs = {
              zoom        : $el.data('zoom') || 16,
              mapTypeId   : google.maps.MapTypeId.ROADMAP
          };
          var map = new google.maps.Map( $el[0], mapArgs );
      
          // Add markers.
          map.markers = [];
          $markers.each(function(){
              initMarker( $(this), map );
          });
      
          // Center map based on markers.
          centerMap( map );
      
          // Return map instance.
          return map;
      }
      
      /**
       * initMarker
       *
       * Creates a marker for the given jQuery element and map.
       *
       * @date    22/10/19
       * @since   5.8.6
       *
       * @param   jQuery $el The jQuery element.
       * @param   object The map instance.
       * @return  object The marker instance.
       */
      function initMarker( $marker, map ) {
      
          // Get position from marker.
          var lat = $marker.data('lat');
          var lng = $marker.data('lng');
          var latLng = {
              lat: parseFloat( lat ),
              lng: parseFloat( lng )
          };
      
          // Create marker instance.
          var marker = new google.maps.Marker({
              position : latLng,
              map: map
          });
      
          // Append to reference for later use.
          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 );
              });
          }
      }
      
      /**
       * centerMap
       *
       * Centers the map showing all markers in view.
       *
       * @date    22/10/19
       * @since   5.8.6
       *
       * @param   object The map instance.
       * @return  void
       */
      function centerMap( map ) {
      
          // Create map boundaries from all map markers.
          var bounds = new google.maps.LatLngBounds();
          map.markers.forEach(function( marker ){
              bounds.extend({
                  lat: marker.position.lat(),
                  lng: marker.position.lng()
              });
          });
      
          // Case: Single marker.
          if( map.markers.length == 1 ){
              map.setCenter( bounds.getCenter() );
      
          // Case: Multiple markers.
          } else{
              map.fitBounds( bounds );
          }
      }
      
      // Render maps on page load.
      $(document).ready(function(){
          $('.acf-map').each(function(){
              var map = initMap( $(this) );
          });
      });
      
    })(jQuery);  
    

    Google Maps API 키 획득 및 설정


    Get an API Key - Google Maps Platform
    위 페이지의 설명에 따라 항목을 선택(또는 제작)하고 Credentials 페이지를 엽니다.Create credentials > API key에서 키를 생성합니다.

    Application restrictions

    HTTP referrers (web sites)

    Website restrictions

    example.com(맵을 설치할 도메인 설정)

    활성화할 API

  • Maps JavaScript API
  • Geocoding API(주소에서 지정된 위치)
  • Place API(모든 유명 장소)
  • 스크립트 불러오기

    functions.php에서 설명합니다.
    function my_api_key() {
      return 'MY_API_KEY';
    }
    function my_acf_google_map_api( $api ) {
      $api['key'] = my_api_key();
      return $api;
    }
    add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');
    
    function add_my_scripts() {
      wp_enqueue_script( 
        'googlemap-script',
        get_theme_file_uri( '/js/googlemap.js' ),
        array( 'jquery' ),
        filemtime( get_theme_file_path( '/js/googlemap.js' ) ),
        true
      );
      wp_enqueue_script(
        'googlemapsapi',
        '//maps.googleapis.com/maps/api/js?key=' . my_api_key(),
        array(),
        '',
        true
      );
    }
    add_action('wp_enqueue_scripts', 'add_my_scripts');
    
    [2020-12-29]
    햄버거 메뉴(스펀지 초밥 지원)는 움직이지 않을 수도 있다jQuery(core, migrate)는 표시WordPress의 초기 상태를 그대로 사용했다.(다음 추가 섹션 삭제)
      wp_deregister_script( 'jquery' );
      wp_enqueue_script(
        'jquery',
        '//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js',
        array(),
        '3.5.1',
        true
      );
    

    사용자 정의 투고 템플릿 보이기


    파일 구조와 스타일 지정 등은 적당히 다시 읽어 주십시오.
    복제single.php제작single-shops.php.
    복제template-parts/content.php제작template-parts/content-shops.php.template-parts/content-shops.php(일부)
        the_content( /*...*/ );
        
        $map = get_field('map');
        if( $map ): ?>
            <div class="acf-map" data-zoom="16">
                <div class="marker" data-lat="<?php echo esc_attr($map['lat']); ?>" data-lng="<?php echo esc_attr($map['lng']); ?>"></div>
            </div>
        <?php endif;
    

    여러 태그 표시


    이 글은 견본의 출처를 공개했다.
    Create Multiple Marker Map from ACF Google Map Location Field from a CPT
    짧은 코드로 이루어진 것도 있다Multiple shortcode [themeprefix_multiple_marker].post_type합치면 바로 사용할 수 있습니다.

    사용자 지정 태그


    Customizing a Google Map: Custom Markers - Google Maps Platform
    이 문장 편집을 참고하시오js/googlemap.js.
    function initMarker( $marker, map ) {
      
        // Get position from marker.
        var lat = $marker.data('lat');
        var lng = $marker.data('lng');
        var latLng = {
            lat: parseFloat( lat ),
            lng: parseFloat( lng )
        };
    
        const iconBase = "//developers.google.com/maps/documentation/javascript/examples/full/images/";
        const icons = {
          parking: {
            icon: iconBase + "parking_lot_maps.png",
          },
          library: {
            icon: iconBase + "library_maps.png",
          },
          info: {
            icon: iconBase + "info-i_maps.png",
          },
        };
        // Create marker instance.
        var marker = new google.maps.Marker({
            position : latLng,
            icon: icons["parking"].icon,
            map: map
        });
      
        // Append to reference for later use.
        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 );
            });
        }
    }
    

    pure JS로 바꿔보도록 하겠습니다.

    js/googlemap.js
    function initMap( acfMap ) {
      var markers = acfMap.querySelectorAll( '.marker' );
      var mapArgs = {
        zoom        : acfMap.dataset.zoom || 16,
        mapTypeId   : google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map( acfMap, mapArgs );
    
      // Add markers.
      map.markers = [];
      markers.forEach( function( mkr, index ){
        initMarker( mkr, map );
      });
      centerMap( map );
      return map;
    }
    
    function initMarker( mkr, map ) {
      var lat = mkr.dataset.lat;
      var lng = mkr.dataset.lng;
      var latLng = {
        lat: parseFloat( lat ),
        lng: parseFloat( lng )
      };
      const iconBase =
     "//developers.google.com/maps/documentation/javascript/examples/full/images/";
      const icons = {
        parking: {
          icon: iconBase + "parking_lot_maps.png",
        },
        library: {
          icon: iconBase + "library_maps.png",
        },
        info: {
          icon: iconBase + "info-i_maps.png",
        },
      };
    
      // Create marker instance.
      var marker = new google.maps.Marker({
        position : latLng,
        icon: icons[ "parking" ].icon,
        map: map
      });
    
      // Append to reference for later use.
      map.markers.push( marker );
    
      // If marker contains HTML, add it to an infoWindow.
      if( mkr.innerHTML ){
        // Create info window.
        var infowindow = new google.maps.InfoWindow({
          content: mkr.innerHTML
        });
    
        // Show info window when marker is clicked.
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open( map, marker );
        });
      }
    }
      
    function centerMap( map ) {
      // Create map boundaries from all map markers.
      var bounds = new google.maps.LatLngBounds();
      map.markers.forEach(function( marker ){
        bounds.extend({
          lat: marker.position.lat(),
          lng: marker.position.lng()
        });
      });
      
      // Case: Single marker.
      if( map.markers.length == 1 ) {
        map.setCenter( bounds.getCenter() );
    
      // Case: Multiple markers.
      } else {
        map.fitBounds( bounds );
      }
    }
    
    document.addEventListener("DOMContentLoaded", function(event){
      var acfMaps = document.querySelectorAll('.acf-map');
      acfMaps.forEach( function( acfMap, index ){
        var map = initMap( acfMap );
      });
    });
    
    js/googlemap.js를 통해 상기wp_enqueue_script()를 읽는다.
    wp_enqueue_script( 
      'googlemap-script',
      get_theme_file_uri( '/js/googlemap.js' ),
      array(),
      filemtime( get_theme_file_path( '/js/googlemap.js' ) ),
      true
    );
    
    함수 참조/wp enqueue script
    따라서 js/googlemap.jsjQuery에 의존하지 않고 このスクリプトが依存するスクリプトのハンドルの配列는 공array(),으로 바뀌었다.

    참고 문장 총결산

  • [WordPress] 플러그인 없이 사용자 정의 게시 형식에 사용자 정의 필드(텍스트 및 이미지)를 추가하는 방법
  • register_post_type() - WordPress Developer Resources
  • WordPress 기고 페이지에 Google Map을 표시하는 방법
  • Field Types > Google Map - ACF Documentation
  • Get an API Key - Google Maps Platform
  • Create Multiple Marker Map from ACF Google Map Location Field from a CPT
  • Customizing a Google Map: Custom Markers - Google Maps Platform
  • 좋은 웹페이지 즐겨찾기