주소로 구글지도를 삽입하는 쇼트코드를 생성하는 방법이다.

API_KEY 부문에는 본인이 발급받은 API KEY를 입력하도록 한다.

사용 방법 {gmap width=’100%’ height=’400px’ zoom=’17’ address=’서울특별시 강남구 테헤란로 200′}

{ 대신 [ 로 써야 된다.

function google_maps_shortcode($atts) {
    // Check if Google Maps JavaScript API is already loaded
    if ( ! wp_script_is( 'google-maps', 'enqueued' ) ) {
        // Google Maps JavaScript API is not loaded, enqueue it
        wp_enqueue_script( 'google-maps', 'https://maps.googleapis.com/maps/api/js?key=API_KEY', array(), null, false );
    }

    $atts = shortcode_atts(
        array(
            'width' => '100%',
            'height' => '400px',
            'address' => '',
            'zoom' => '17'
        ),
        $atts,
        'gmap'
    );

    // Generate a unique ID for the map container
    $map_id = 'gmap_' . substr(sha1(rand()), 0, 8);

    // Sanitize attributes
    $width = esc_attr($atts['width']);
    $height = esc_attr($atts['height']);
    $address = esc_attr($atts['address']);
    $zoom = intval($atts['zoom']);

    // Generate the map HTML
    $map = '
    <div id="'.$map_id.'" style="height: '.$height.'; width: '.$width.';"></div>
    <script>
        function initMap_'.$map_id.'() {
            var address = "'.$address.'";
            var mapOptions = {
                zoom: '.$zoom.',
                center: {lat: 0, lng: 0}
            };
            var map = new google.maps.Map(document.getElementById("'.$map_id.'"), mapOptions);
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({"address": address}, function(results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location
                    });
                } else {
                    alert("지정된 위치를 찾을 수 없습니다: " + status);
                }
            });
        }

        // Load the map when the Google Maps API is ready
        function loadGoogleMapScript_'.$map_id.'() {
            initMap_'.$map_id.'();
        }
        window.addEventListener("load", loadGoogleMapScript_'.$map_id.');
    </script>   
    ';

    return $map;
}
add_shortcode('gmap', 'google_maps_shortcode');

#구글지도 #스니펫 #쇼트코드 #워드프레스

Author: 모요
댓글

댓글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

*

©2024 MOYO Blog with DAON Consulting Co,LTD.

CONTACT US

We're not around right now. But you can send us an email and we'll get back to you, asap.

보내는 중입니다..

로그인하세요.

계정 내용을 잊으셨나요 ?