{"id":145351,"date":"2015-09-11T11:00:41","date_gmt":"2015-09-11T15:00:41","guid":{"rendered":"http:\/\/premium.wpmudev.org\/blog\/?p=145351"},"modified":"2015-09-11T03:42:04","modified_gmt":"2015-09-11T07:42:04","slug":"google-maps-shortcode","status":"publish","type":"post","link":"https:\/\/wpmudev.com\/blog\/google-maps-shortcode\/","title":{"rendered":"Adding Google Maps to WordPress with Your Own Quick Shortcode"},"content":{"rendered":"<p>If you often use <a href=\"https:\/\/wpmudev.com\/blog\/how-to-add-maps-to-wordpress\/\" target=\"_blank\" rel=\"noopener\">Google Maps<\/a> on your site, or just want an easier way to embed maps in posts and pages, here&#8217;s how you can do it with your own shortcode.<\/p>\n<p>We&#8217;ve covered the\u00a0<a href=\"https:\/\/wpmudev.com\/blog\/a-guide-to-creating-wordpress-shortcodes\" target=\"_blank\">basics of creating shortcodes<\/a> before, so today we&#8217;ll put this knowledge into practice by creating a Google Maps shortcode you can use anywhere on your site.<\/p>\n<h3>Creating a Shortcodes Plugin<\/h3>\n<p>In this tutorial, we&#8217;re going to create a plugin. If you haven&#8217;t done it before, check out our easy to follow\u00a0<a href=\"https:\/\/wpmudev.com\/blog\/wordpress-plugin-development-guide\/\" target=\"_blank\">getting started with plugins guide<\/a>.<\/p>\n<p>But if you want the nutshell version&#8230;<\/p>\n<ol>\n<li>Create a folder named <code>my-google-maps-shortcode<\/code> in your site&#8217;s &#8220;plugins&#8221; directory.<\/li>\n<li>Create a file named <code>my-google-maps-shortcode.php<\/code> in it and paste the following at the very top:<\/li>\n<\/ol>\n<div class=\"gist\" data-gist=\"e988c533171f06b08b5ee24645df4944\" data-gist-file=\"basic.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/e988c533171f06b08b5ee24645df4944.js?file=basic.php\">Loading gist e988c533171f06b08b5ee24645df4944<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>That&#8217;s all! You should now be able to activate the plugin in WordPress and get started.<\/p>\n<p>In this tutorial, I will be using this custom plugin (which you can download at the end of this article) along with Twenty Fifteen, the current default WordPress theme.<\/p>\n<h3>The Google Maps JavaScript API<\/h3>\n<p>To get going, we&#8217;ll be using the <a href=\"https:\/\/developers.google.com\/maps\/documentation\/javascript\/overview\" target=\"_blank\">Google Maps Javascript API<\/a>. You&#8217;ll need a free API Key so follow the steps in the documentation\u00a0to get one.<\/p>\n<p>Once you have an API key there are three things you need to do next:<\/p>\n<ul>\n<li>Link the Google Maps Javascript,<\/li>\n<li>Create an empty element for the map, and<\/li>\n<li>Create a map in the element using basic JavaScript.<\/li>\n<\/ul>\n<p>Step one involves enqueueing the official JavaScript file with a special parameter that holds the API key.<\/p>\n<p>The general form is: <code>http:\/\/maps.googleapis.com\/maps\/api\/js?key=API_KEY8&amp;callback=initMap<\/code>.<\/p>\n<p>To enqueue this script we&#8217;ll use the <code>wp_enqueue_scripts<\/code> hook in our plugin.<\/p>\n<div class=\"gist\" data-gist=\"e8c130a5f7f2a161e9cb15a2bdaea5c0\" data-gist-file=\"enqueue.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/e8c130a5f7f2a161e9cb15a2bdaea5c0.js?file=enqueue.php\">Loading gist e8c130a5f7f2a161e9cb15a2bdaea5c0<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>When defining the location of the script, note that I&#8217;ve left out the protocol (HTTP) and the colon. This is recommended because the request will use the more secure HTTPS if your site uses it, otherwise it will fall back on HTTP.<\/p>\n<h3>The Basic Shortcode<\/h3>\n<p>Our shortcode will need to output an empty element and some JavaScript. Depending on the parameters of the shortcode we can change the JavaScript to suit\u00a0our requirements.<\/p>\n<p>Let&#8217;s create a very simple shortcode now, which will just output the empty element.<\/p>\n<div class=\"gist\" data-gist=\"1336f75f746f7201c87decfda66e8bb9\" data-gist-file=\"add_shortcode.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/1336f75f746f7201c87decfda66e8bb9.js?file=add_shortcode.php\">Loading gist 1336f75f746f7201c87decfda66e8bb9<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>As you can see, I&#8217;ve created a unique ID for each element. The ID of this element doesn&#8217;t have to be consistent between page loads, but it should be unique on the page to make sure the JavaScript can target it later on.<\/p>\n<p>To get a unique ID I&#8217;ve taken a string as the base which contains the local time. Right now this would be &#8220;Google Map1440658708&#8221;. I then generated an sha1 hash from it which looks like this: 194567aaa0785d40c4af5a5536533497bf49541b.<\/p>\n<p>I created a shorter string from this mess by defining a random starting point (between character 2 and 10) and a random length for the string (between 5 and 8).<\/p>\n<p>At the end of the day, our empty element will look something like this: <code>&lt;div class=\"map\" id=\"map-7f51e\"&gt;&lt;\/div&gt;<\/code><\/p>\n<h4>Hard-Coded JavaScript<\/h4>\n<p>Let&#8217;s add a basic Hello World example by hard-coding a specific location and view.<\/p>\n<p>The following will show a map centered on Yellowstone National Park in Wyoming (a thoroughly awesome place!).<\/p>\n<div class=\"gist\" data-gist=\"f5d9fcc300c04f6cdb4eaaddc3be7539\" data-gist-file=\"basic-map.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/f5d9fcc300c04f6cdb4eaaddc3be7539.js?file=basic-map.php\">Loading gist f5d9fcc300c04f6cdb4eaaddc3be7539<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>I used output buffering to make the code a bit clearer. Everything after the <code>ob_start()<\/code> function goes into the buffer instead of being output.<\/p>\n<p>You can then capture the buffer and clear it with <code>ob_get_start()<\/code>\u00a0\u2013 a nice way to get complex HTML generated by PHP into a variable.<\/p>\n<figure id=\"attachment_145354\" class=\"wp-caption aligncenter\" data-caption=\"true\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-145354\" src=\"https:\/\/wpmudev.com\/blog\/wp-content\/uploads\/2015\/08\/Screen-Shot-2015-08-27-at-09.13.52.png\" alt=\"Map Shortcode Example\" width=\"735\" height=\"861\" \/><figcaption class=\"wp-caption-text\">An example of a map generated by our shortcode<\/figcaption><\/figure>\n<p>Our JavaScript contains a function named <code>initMap<\/code>. This function comes from the very end of our JavaScript file reference which is <code>callback=initMap<\/code>. If you rename the callback in the file, you&#8217;ll need to rename your function as well.<\/p>\n<p>The function creates a new <code>google.maps.Map<\/code> object, passing it the element and some parameters. The two parameters we&#8217;re using are <code>center<\/code>, which defines the center point of the map, and zoom, which defines the zoom.<\/p>\n<p>At this point, all we have to do is add parameters to the shortcode and make sure they are picked up. In a real world scenario, I would advise moving the inline styling into a CSS file, of course.<\/p>\n<h3>Adding Shortcode Parameters<\/h3>\n<p>To make the example more useful, let&#8217;s allow users to define the center point with a lat and lng parameter and set the zoom level. While there, let&#8217;s make sure the map height can also be changed.<\/p>\n<div class=\"gist\" data-gist=\"ce31367a6749ab51d68f01f1057c172f\" data-gist-file=\"map.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/ce31367a6749ab51d68f01f1057c172f.js?file=map.php\">Loading gist ce31367a6749ab51d68f01f1057c172f<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>As you can see, it&#8217;s a matter of using <code>shortcode_atts<\/code> to grab parameters and then replacing hard-coded values with PHP variables. I can now use <code>[map lat='47.4925' lng='19.0514' zoom='10' height='200px']<\/code> to create a narrower map, centered on Budapest.<\/p>\n<figure id=\"attachment_145355\" class=\"wp-caption aligncenter\" data-caption=\"true\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-145355\" src=\"https:\/\/wpmudev.com\/blog\/wp-content\/uploads\/2015\/08\/Screen-Shot-2015-08-27-at-09.25.45.png\" alt=\"Modified Map Shortcode\" width=\"735\" height=\"234\" \/><figcaption class=\"wp-caption-text\">A modified map shortcode with parameters<\/figcaption><\/figure>\n<p>Creating awesome functionality with shortcodes is easy, especially when coupled with great APIs like Google Maps.<\/p>\n<p>There is a <em>lot<\/em> more room for improvement, like using addresses instead of coordinates using the Geocoding API, and adding Google Street View, pins and more.<\/p>\n<p>You can download our own\u00a0<a href=\"https:\/\/github.com\/wpmudev\/google-maps-free\" rel=\"noopener\" target=\"_blank\">Google Maps plugin<\/a>, which will give you access to traffic overlays, street view, responsive maps, current location, and more.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you often use Google Maps on your site, or just want an easier way to embed maps in posts and pages, here&#8217;s how to do it with your own shortcode. (It really doesn&#8217;t get any easier than this)<\/p>\n","protected":false},"author":344049,"featured_media":145239,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"blog_reading_time":"","wds_primary_category":0,"wds_primary_tutorials_categories":0,"footnotes":""},"categories":[263],"tags":[9885,1081],"tutorials_categories":[],"class_list":["post-145351","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-google","tag-shortcodes"],"_links":{"self":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/145351","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/users\/344049"}],"replies":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/comments?post=145351"}],"version-history":[{"count":10,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/145351\/revisions"}],"predecessor-version":[{"id":209280,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/145351\/revisions\/209280"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/media\/145239"}],"wp:attachment":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/media?parent=145351"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/categories?post=145351"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/tags?post=145351"},{"taxonomy":"tutorials_categories","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/tutorials_categories?post=145351"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}