Embed the new Google Maps without a plugin or shortcode
-
Hi,
There are a lot of tutorials about embedding Google Maps in your posts, but after a long and painful research, I notice that every single tutorial was about embedding **THE OLD** Google Maps platform… the one with the url scheme ‘maps.google.com’.
**THE NEW** Google Maps scheme (
https://www.google.com/maps/place/
) is completely different, and there almost no documentation on how to make it work in WordPress.So, here is a quick tutorial on how to embed **THE NEW** Google Maps in WordPress posts without a plugin and just pasting the map url in the post body:
1. First, you need an API Key from Google. Follow the instructions at https://developers.google.com/maps/documentation/embed/guide#api_key.
2. Once you have your API Key, we can get into the code. In your favorite theme, open functions.php and add:
<?php wp_embed_register_handler( 'googlemapsv1', '#https?://www.google.com/maps/place/(.*?)/#i', 'wpgm_embed_handler_googlemapsv1' ); function wpgm_embed_handler_googlemapsv1( $matches, $attr, $url, $rawattr ) { if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) { $width = (int) $rawattr['width']; $height = (int) $rawattr['height']; } else { list( $width, $height ) = wp_expand_dimensions( 425, 326, $attr['width'], $attr['height'] ); } return apply_filters( 'embed_googlemapsv1', "<iframe width='{$width}' height='{$height}' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://www.google.com/maps/embed/v1/place?q=" . esc_attr($matches[1]) . "&key=***YOUR-API-KEY***'></iframe>" ); }; ?>
Be sure to replace ***YOUR-API-KEY*** with your KEY. Save & close.
3. Test the new code by adding a new post and just pasting a google maps url like this one from The White House:
https://www.google.com/maps/place/The+White+House/@38.896278,-77.0306687,17z/data=!3m1!4b1!4m2!3m1!1s0x89b7b7bcdecbb1df:0x715969d86d0b76bf
That works the same way as just using:
https://www.google.com/maps/place/The+White+House/
The RegEx can be tweaked to allow different URL schemes for the four new modes, detailed here: https://developers.google.com/maps/documentation/embed/guide#modes.
This method only works for ‘place’ mode, but reading the documentation will get you on track to make the ‘directions’, ‘search’ and other modes working.
That’s it. I hope it works for you guys (and excuse my english). Any contributions for the code will be appreciated.
- The topic ‘Embed the new Google Maps without a plugin or shortcode’ is closed to new replies.