WPLake > Learning Hub > Embedding Map in WordPress: Comprehensive Guide

Embedding Map in WordPress: Comprehensive Guide

An extensive guide to embedding maps in WordPress: covers Google and OSM vendors, suitable for all use cases, and includes both plugin options and custom coding.

Key Points at a Glance

  1. To embed Google Maps, an API key is required, and there is a free basic option with additional charges for higher usage.
  2. OpenStreetMap (OSM) is completely free and open-source, with no costs associated with embedding or using the API.
  3. Iframe Embedding provides a straightforward method using static HTML, but it lacks features for customizing dynamic markers or zoom control.
  4. JavaScript API Embedding enables advanced customization and interaction, including custom markers and popups.
  5. WordPress Plugins, such as WP Google Maps and Leaflet Map, simplify the process of embedding and customizing maps without the need for coding.
  6. Meta Field Plugins allow maps to be integrated into specific post types and content layouts, such as Advanced Custom Fields.
  7. Leaflet.js, a lightweight library, allows the creation of interactive maps with OpenStreetMap data, accessible via CDN or local hosting.
  8. Custom Coding provides extensive control over map functionality and appearance, but it necessitates coding skills for integration.

Table of Contents

Before tackling a task, it's important to explore your options and understand their limits. Whether you're a developer handling an advanced use case or a website owner, a deeper look at how to embed a map in WordPress will assist you in finding the right solution.

Before diving into the methods for embedding, let's quickly compare the two most popular map providers to help you choose the best one for your needs.

1. Google Maps vs. Open Street Map

Google Maps and OpenStreetMap (OSM) are the dominant map providers. While there are other map vendors like Mapbox, they are often paid services and are typically used for specialized requirements.

1.1) Google Maps - well-known vendor with a limited free tier

Google Maps, a widely used mapping service, has transitioned from being entirely free to implementing a tiered pricing model. Currently, Google Maps offers limited free embedding and requires a paid plan for extensive usage.

A while ago, Google Maps allowed unlimited free embedding, but now, each Google Map instance requires an API key. This requires creating a Google Cloud account and configuring the mapping service.

Upon setup, all users get a monthly credit of $200 for free map embedding. Any usage exceeding this limit will mean additional charges. While embedding Google Maps with an iframe is still free, it’s worth noting that you won’t have any customization options.

For detailed information on pricing and usage, please refer to Google's official pricing details.

Note: The focus here is specifically on embedding Google Maps and not the general Google Maps website, which remains accessible to all.

In summary: Google Maps is a suitable option for those who specifically need to display Google Maps, have a limited number of visitors per month, or are willing to cover the costs for higher usage.

1.2) Open Street Map - open source and completely free

OpenStreetMap (OSM) is a free, open geographic database updated and maintained by a community of volunteers through open collaboration.

The map is available to everyone via the openstreetmap.org website and supports multiple layers. Layers represent different ways of presenting the map, such as geographic, political, or transport, much like how maps were categorized in school.

Thanks to its open-source nature, embedding this map is completely free, and its advanced functionalities through APIs like Leaflet are also free of charge.

In most cases, OpenStreetMap is the go-to option unless you have a specific need for Google Maps.

2. Embedding via Iframe vs. embedding via JavaScript API

When it comes to embedding maps on a website, you generally have two main options: using an iframe or a map API.

2.1) Embedding via Iframe

This is the easiest method, and it works on any website right out of the box. It relies on the iframe HTML element, which allows you to display other websites (or pages) within your web page. You just need to set up the map, copy the embed URL, and drop it into an iframe on your site.

However, there are some drawbacks: it doesn’t support all map options. For instance, you can’t dynamically define markers or place multiple markers on a single map. Additionally, you can’t fine-tune the map, such as by limiting the maximum zoom level or defining a custom map marker icon.

It means that it's limited solely to the generic options. To embed OSM, just visit OpenStreetMap, hit the share button in the top-right, pick the HTML option, and add a marker if you want. The copied HTML can be pasted onto any page of your website.

The HTML will look like this:

<iframe width="425" height="350" 
src="https://www.openstreetmap.org/export/embed.html
?bbox=-12.886962890625002%2C36.60670888641817
%2C5.460205078125001%2C44.000717834282774
&amp;layer=cyclemap
&amp;marker=40.40513069752789%2C-3.71337890625" 
style="border: 1px solid black">
</iframe>

2.2) Embedding via JavaScript API

While embedding an iframe is a great solution for simple use cases, advanced applications require using a JavaScript API.

What does this mean? Instead of adding a static HTML snippet to our website, we need to integrate a JavaScript API (library), either official or from the community, that works with the chosen map provider. This API will dynamically handle the map settings.

Though this approach is a bit more complex, it provides full control over the map. Whether you need to set up custom markers, add multiple markers, or display custom popups when markers are clicked, the API allows for all of these features.

The most popular JavaScript library for OpenStreetMap is Leaflet, while Google provides its own JavaScript library, which requires an API key, as mentioned earlier.

Note: If you’re not experienced with JavaScript or simply don’t have the time to dive into it, don’t worry: WordPress plugins are available that manage the API for you, offering a hassle-free way to embed and customize maps.

3. How to embed a map in WordPress using iframe

Keep in mind that this approach is suitable only for straightforward use cases, such as a simple contact location map that doesn't require any deep customization. The first thing we should do in this case is to obtain the embed code.

3.1) Getting iframe code

A) For Google Maps:

Step 1: Search for the Location on Google Maps

  1. Go to Google Maps and search for the location you want to embed.
  2. Once the location appears, click on the "Share" button, represented by an icon of a paper plane.
  3. A popup will appear with two tabs: "Send a link" and "Embed a map." Click on the "Embed a map" tab.

Step 2: Customize the Map

  1. In the "Embed a map" tab, you'll see a preview of the map with a dropdown to select the size of the map (Small, Medium, Large, or Custom size).
  2. Choose the appropriate size for your WordPress page. You can also specify custom dimensions if you have specific size requirements.
  3. After selecting the size, copy the iFrame code provided in the box below the preview.

B) For OpenStreetMap:

Step 1: Choose the Location on OpenStreetMap

  1. Go to OpenStreetMap and find the location you want to display.
  2. Once you’ve centered the map on the desired location, click on the "Share" icon, typically represented by an arrow.

Step 2: Configure and Obtain the iFrame Code

  1. In the share popup, you’ll see two main options: a URL for sharing and an HTML snippet for embedding the map.
  2. Above the HTML code, there’s a checkbox labeled “Include marker.” Toggle this checkbox to automatically add a marker at the center of the map. Note: once the marker appears, you can move this marker to the exact place you need.
  3. After checking the "Include marker" option, the iFrame code will update to include the marker coordinates.

3.2) Embedding the iFrame's map in WordPress

  1. Copy the iFrame code received in the first step
  2. Log in to your WordPress dashboard and navigate to the page or post where you want to embed the map.
  3. Add a "Custom HTML" block by clicking the "+" button and selecting it from the block options.
  4. Paste the iFrame code into the Custom HTML block.
  5. Preview the page to ensure the map and marker appear correctly. If everything looks as expected, publish or update your page.

4. How to embed a map in WordPress using JavaScript API

Using the JavaScript API to embed maps gives you way more flexibility and customization than iframes do. This approach allows you to create dynamic, interactive maps with extensive control over map features and styling.

You can achieve this either by using WordPress plugins or by directly coding the integration. Plugins make it easy to add maps to your site without touching any code. There are two main approaches when using plugins: specific map creation plugins and meta field plugins with map-related field types.

4.1) Embedding maps using specific map creation WordPress plugins

Map creation plugins are designed specifically to help you embed maps into your WordPress pages or posts. These plugins are ideal when you need to embed a map on a single page or when you don't require additional meta fields for your content.

When to use:

  • You need to add a map to a single page or post.
  • You don’t have any other custom fields or metadata requirements.
  • You prefer a quick, easy-to-use solution without additional setup.

Popular plugins:

  • WP Google Maps is widely used for embedding Google Maps. With the plugin's user interface, you have the ability to generate personalized maps, insert markers, and adjust various map settings.
  • Leaflet Map is a robust plugin that connects with the Leaflet.js library, simplifying the process of embedding OpenStreetMap (OSM) on your WordPress website. Additionally, this plugin accommodates advanced functionalities such as custom markers, layers, and pop-ups.

How to Use:

  1. Install and activate the plugin from the WordPress plugin repository.
  2. Go to the plugin’s settings and set it up according to your needs.
  3. Create a map following the chosen plugin instructions (see its readme).
  4. Once your map is ready, use the provided shortcode or Gutenberg block to embed it into the target WordPress page or post.

4.2) Embedding maps using WordPress meta field plugins

Meta fields plugins, such as Advanced Custom Fields, Meta Box, or Pods, allow you to add custom fields to your WordPress content types, including maps. This approach is particularly useful when you need to embed maps across multiple items (e.g., multiple custom post types) or when you’re already using a meta fields plugin for other purposes.

Tip: if you aren't sure which meta plugin to use, check out our meta field plugins comparison.

When to Use:

  • You have multiple content items (e.g., custom post types) that need maps.
  • You’re already using or planning to use a meta fields plugin for additional custom fields.
  • You require a more integrated solution where maps are part of the content structure.

How to use:

Regardless of the chosen meta plugin, the general usage scheme is the same: it involves adding a map field to the target screen (your CPT or page) and displaying the field's value in the desired location.

To display the value, you can use the built-in tools of the chosen plugin, or you can use the Advanced Views Framework (available as a free plugin), which supports all the mentioned meta plugins and makes displaying the map field incredibly simple.

Check out our ACF Google Map Field article for a detailed step-by-step guide. If you wish to use OpenStreetMap, don't worry - there is an ACF add-on, as mentioned here, that provides this field type as well.

4.3) Embedding Google Maps using custom coding

For more control over map functionality and appearance, embedding maps using JavaScript API is the way to go. This method requires some coding knowledge but offers unmatched flexibility.

Google Maps JavaScript API allows you to create highly customized maps with a variety of features. There is an official general (non-WP) tutorial, that describes the API usage in detail. Below we provide a basic example of how to use the API with WordPress:

1. Get an API Key

Following the official tutorial to get your API key.

2. Add the API script to your WordPress theme

Add the following code to your theme’s functions.php file to enqueue the Google Maps API:

function enqueue_google_maps_api() {
 // todo put your api key here
    wp_enqueue_script('google-maps-api', 'https://maps.googleapis.com/maps/api/js
?key=YOUR_API_KEY&callback=initMap', null, null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_google_maps_api');

3. Create the Map:

Add the following JavaScript code to your theme’s javascript file:

function initMap() {
    var location = {lat: -34.397, lng: 150.644};
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: location
    });
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
}

4. Add an empty <div> with an ID of the map where you want the map to appear in your WordPress template:

<div id="map" style="height: 400px; width: 100%;"></div>

That's it. Once the map loads, it’ll call the callback we set up in the URL, and then the map will appear.

For more advanced features and customization options, check the official tutorial.

4.4) Embedding OpenStreetMaps using custom coding

1. Add the Leaflet.js library to your theme

OpenStreetMap is a data vendor, which means it doesn't offer a dedicated JS library for map presentation. Fortunately, there is a nice and renown library for this case - Leaflet.

Leaflet.js is a popular and lightweight JavaScript library used to create interactive maps with OpenStreetMap data. You can either load Leaflet.js from a CDN or download it and host it locally on your server.

Option 1: Using CDN

Add the following code to your theme’s functions.php file to enqueue the Leaflet.js library from a CDN:

function enqueue_leaflet_js() {
    wp_enqueue_style('leaflet-css', 'https://unpkg.com/[email protected]/dist/leaflet.css');
    wp_enqueue_script('leaflet-js', 'https://unpkg.com/[email protected]/dist/leaflet.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_leaflet_js');

Option 2: Downloading and Hosting Locally

Alternatively, you can download Leaflet.js and host it locally:

  1. Download the latest Leaflet.js files from the Leaflet website.
  2. Upload the leaflet.js and leaflet.css files to your theme's directory, typically in a js and css folder, respectively.
  3. Update your functions.php to enqueue these local files:
function enqueue_local_leaflet_js() {
    wp_enqueue_style('leaflet-css', get_template_directory_uri() . '/css/leaflet.css');
    wp_enqueue_script('leaflet-js', get_template_directory_uri() . '/js/leaflet.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_local_leaflet_js');

2. Create the map in JavaScript

Next, add the following JavaScript code to your theme’s JavaScript file to initialize the map:

function initOSMMap() {
    var map = L.map('osm-map').setView([51.505, -0.09], 13); // Default view: London

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    var marker = L.marker([51.505, -0.09]).addTo(map)
        .bindPopup('A pretty popup.<br> Easily customizable.')
        .openPopup();
}
document.addEventListener('DOMContentLoaded', initOSMMap);

This script initializes the map centered on London with a zoom level of 13. A marker is added to the map, with a popup that can be easily customized.

3. Add the map container to your template

In the WordPress template where you want the map to appear, add an empty <div> with an ID for the map:

<div id="osm-map" style="height: 400px; width: 100%;"></div>

This will create a responsive map container with a height of 400px and full width.

5. Advanced: How to display all WordPress CPT items on a single map

Displaying all Custom Post Type (CPT) items on a single map in WordPress is an advanced task that can be extremely useful in various scenarios.

For instance, if you have an "events" CPT where each event has a map meta field storing coordinates, you might want to display all of these events as markers on a single map. Additionally, you can set up marker popups to display event details when clicked.

While you could achieve this with either Google Maps or OpenStreetMap, we will use OpenStreetMap with the Leaflet.js library. As we mentioned earlier, Leaflet is a flexible and accessible option, especially for those who prefer an open-source solution.

For this task, we'll query the CPT items, pass the coordinates to JavaScript, and initialize the map with markers.

To simplify the process, we’ll use the Advanced Views Framework. This framework is designed to simplify querying and displaying tasks in WordPress, offering smart templates and handling JavaScript assets, so we won't need to manage these aspects manually.

Let's get started with the step-by-step guide:

5.1) Ensure you have a Custom Post Type with coordinates meta fields

Make sure your Custom Post Type (e.g., "events") has some items with coordinates stored in meta fields. These coordinates might come from fields like ACF Google Maps or OpenStreetMap fields.

Note: The meta fields store only the coordinates, so you can use 'Google Maps' for editors while displaying the results with an OSM map, or vice versa.

5.2) Install the Advanced Views Framework

Install and activate the Advanced Views Framework plugin. This plugin introduces two key concepts: "Views" and "Cards".

  • Views - handle the display of individual items.
  • Cards - manage the query and general layout of items.

Enable the File System Storage option to store Views and Cards inside your theme. This allows them to be edited in an IDE. Alternatively, you can edit them using the framework’s built-in onsite editor.

5.3) Create a View for the map marker

Create a new View to define how each map marker will appear. In this View, include the following fields:

  • Map Meta Field: The coordinates where the marker will be placed.
  • Post Title: To be displayed in the marker popup.
  • Featured Image: To add visual context to the marker popup.
  • Excerpt: To provide a brief description of the marker popup.

This View will be used to define the marker and populate the popup content that appears when users click on a marker.

5.4) Create a Card for the CPT Query

Create a new Card to handle the query and layout of all CPT items.

In the Card:

  • Select the View you created in the previous step to control how each item is displayed.
  • Set the Post Type to your custom post type (e.g., "events").
  • Set the Limit field to -1 to query all items without any limit.

Save the Card and copy the generated shortcode.

5.5) Paste the Card shortcode into the target page

  • Paste the shortcode into the page where you want to display the map.
  • Save the page and visit it to ensure that the CPT items are being displayed with their details.

At this stage, don’t worry if the layout looks chaotic; we’re primarily ensuring that the query is correct. If you don’t see the items, return to the Card settings and check your configuration.

5.6) Map creation in Card

Now it's time to master the map. Download the Leaflet JS and CSS code from the official website, and upload them to some folder in your theme.

Put the following code into the Card's template (in the custom.twig file, or using the Card's code editor):

<projects-map class="{{ _card.classes }}projects-map">
    <div class="projects-map__items">
        {% for post_id in _card.post_ids %}
            [acf_views view-id="{{ _card.view_id }}" object-id="{{ post_id }}" class="projects-map__item"]
        {% endfor %}
    </div>

    <div class="projects-map__wrapper">
        <div class="projects-map__map"></div>
    </div>

</projects-map>

We also need to add some basic styles (put into the Card's style.css file). Make sure you've replaced YOUR_THEME in the import line below with yours, and replace the rest of the path with the path, where you've uploaded the leaflet's assets.

@import url('/wp-content/themes/YOUR_THEME/assets/leaflet/leaflet.css');

#card {
    display: block;

    #this__items {
        display: none;
    }

    #this__wrapper {
        width: 100%;
        height: calc(60vh);
        position: relative;
    }

    #this__map {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        border: 0;
        outline: none;
    }
}

Now it's time to create the JS code, which will init the map. Thanks to Advanced Views Framework, the JS code will be wrapped into the WebComponent and enqueued on the target page, so we don't need to worry about it.

import '/wp-content/themes/YOUR_THEME/assets/leaflet/leaflet.min.js';

let _this = this;

function setupMap(element) {
    let currentZoom = window.innerWidth < 992 ?
        0.75 :
        2;
    let minZoom = window.innerWidth < 992 ?
        0.25 :
        2;

    let map = L.map(element, {
        // todo map settings
        minZoom: minZoom,
        maxZoom: 8,
        attributionControl: false,
        zoomControl: false,
        zoomSnap: 0.25, // allow fractional zoom levels
        worldCopyJump: true,
    }).setView([40, 10], currentZoom);

    if (window.innerWidth < 992) {
        map.fitWorld();
    }

    // todo you can choose any provider from the following list https://leaflet-extras.github.io/leaflet-providers/preview/

    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        bounds: [[-75, -180], [81, 180]],
    }).addTo(map);

    return map;
}

function setupMarkers(map, items) {
    let icons = {};

    let popupMaxWidth = window.innerWidth < 992 ?
        300 :
        600;

    items.forEach(item => {
        let lat = item.dataset['lat'] || 0;
        let lng = item.dataset['lng'] || 0;

        if (false === icons.hasOwnProperty(icon)) {
            icons[icon] = L.icon({
                // iconUrl: '', // todo you can put use your own icon url here
                iconSize: [49, 49], // size of the icon
                iconAnchor: [20, 49], // point of the icon which will correspond to marker's location
                popupAnchor: [5, -49] // point from which the popup should open relative to the iconAnchor
            });
        }

        let markerPosition = L.latLng(lat, lng);

        let marker = L.marker(markerPosition, {
            icon: icons[icon]
        }).bindPopup(item.outerHTML, {
            maxWidth: popupMaxWidth,
        });

        marker.addTo(map);
    });
}

function init() {
    let map = setupMap(_this.querySelector('.projects-map__map'));

    setupMarkers(map, _this.querySelectorAll('.projects-map__item'));
}

init();

Remember to update the import line by replacing the YOUR_THEME with your specific path. Also, look for the 'todo' marks in the code, which highlight the areas that can be customized based on your requirements.

Explanation of the JavaScript code

The first step in this code snippet involves importing the Leaflet.js library from a local file. Following that, the map is initialized to dynamically adjust zoom levels based on the screen size.

The function setupMap is in charge of configuring the map's appearance and behavior, establishing a default view, and incorporating OpenStreetMap tiles. The map is adaptable, modifying its zoom and layout to accommodate the user's screen size for optimal display on both large and small devices.

Next, the function setupMarkers loops through a list of HTML elements representing CPT items (e.g., events), each of which contains latitude and longitude data. For each item, it produces a map marker, customizes the marker's icon if necessary, and connects a popup that shows the HTML content of the item when the marker is clicked.

Finally, the function init consolidates everything by invoking these setup functions and situating the markers on the map.

5.7) Marker details in View

The final step involves configuring the markers by adjusting the View's template. Start by duplicating the automatically generated template from default.twig and saving it as a new file named custom.twig within your View.

Next, include data-lat and data-lng attributes at the top of the template:

<project-map-item
    class="{{ _view.classes }} project-map-item project-map-item--id--{{ _view.id }} project-map-item--object-id--{{ _view.object_id }}"
    data-lat="{{ location.lat }}" data-lng="{{ location.lng }}">

Be sure to replace location with the correct field identifier for your coordinates. You can find this identifier by examining the default template.

These data-lat and data-lng attributes are crucial, as they will be used by the Card's JavaScript to initialize the markers on the map. The entire HTML of the View will be used as the content for the marker's popup. Feel free to customize the HTML markup and add custom CSS to achieve the desired appearance.

5.8) Summary

And that’s it! After configuring everything, visit the target page where you placed the shortcode and reload it. You should now see an OpenStreetMap (OSM) map displaying all your items as markers, with popups that show their details when clicked.

This is a foundational example, and you can extend it according to your needs. For instance, if you want to use custom marker icons for each item, you can add a map marker image field to your CPT items and pass the icon's URL via data attributes, just as we did with the location.

Leaflet's flexibility allows for endless customization possibilities. If your map contains many WordPress CPT items, you might consider using the Marker Cluster plugin, which groups markers together and only separates them when the map is zoomed in sufficiently.

With Leaflet, the possibilities are truly endless!

6. Conclusions

Choosing the right technique for integrating maps is essential for customizing your WordPress website, whether you're overseeing a basic contact page or a dynamic map featuring multiple locations.

The decision between Google Maps and OpenStreetMap hinges on your needs: Google Maps offers comprehensive features at a price, whereas OpenStreetMap presents a free, community-driven alternative.

Utilizing an iframe is a rapid and straightforward solution for simple map embeds. However, if customization and interactivity are key priorities, employing a JavaScript API, either through plugins or custom coding, provides much greater flexibility.

For developers and advanced users, integrating maps using APIs such as Leaflet.js for OpenStreetMap or the Google Maps JavaScript API enables extensive customization, seamlessly integrated into WordPress through custom code or plugins. In contrast, WordPress plugins offer a user-friendly method for embedding and managing maps without requiring extensive coding knowledge.

Stuck with development or facing an issue?

WPLake offers affordable on-demand website development and design.

No matter the size of your project - contact us now, and we'll get it done for you!

Get assistance now

FAQ mode

/

Learning mode

  1. What are the distinctions between utilizing an iframe and a JavaScript API for embedding maps?

    Embedding maps using an iframe provides basic customization options, whereas a JavaScript API provides more advanced features such as custom markers and interactive elements, necessitating a greater understanding of coding.

  2. Is it possible to incorporate maps into custom post types in WordPress?

    Indeed, you have the option to utilize meta field plugins such as Advanced Custom Fields to add map fields to custom post types and exhibit them on your website.

  3. Which WordPress plugins are beneficial for map embedding?

    WP Google Maps is a well-regarded plugin for integrating Google Maps, while Leaflet Map is another popular choice for OpenStreetMap integration. If you are planning to use it in a custom post type, Advanced Views Framework with meta fields is an excellent option.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

Course navigation: WordPress Beginner

Content links (34)

About the Author

Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly


    Got it