주소로 구글지도를 삽입하는 쇼트코드를 생성하는 방법이다.
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');
