Skip to content
Menu
Quedank: Simplify
  • Home
  • Recent Posts
  • Computer Science
    • Servers and Hosting
    • Programming and Coding
    • Web
  • Digital Marketing
  • Multimedia
Quedank: Simplify
April 17, 2021February 10, 2022

Loop Google Maps Markers and Coordinates from WordPress Posts

-Advertisement-

This article is for you if you’re trying to figure out how to render a Google map in your WordPress website, with multiple markers where the coordinates are coming from the posts or custom post types.

Scenario: Let’s say you’ve created a custom post type called “Restaurants”. You have custom fields in that post where you enter the restaurant’s coordinates and you want to mark in a Google map the location of each restaurant using those coordinates.

You can use a plugin called Advanced Custom Fields to add a “Map” group field that accepts the latitude and longitude coordinates of the restaurant in its sub fields.

Sample custom fields using ACF, a “Map” group field in the custom post type Restaurant

We will be able to use these coordinates to create a marker for each restaurant and plot them on a Google map.

You can use both PHP and JavaScript to do this. The sample code we have below uses PHP to create the post loop and uses JavaScript to render the map and the markers.

<!-- Your map will be rendered here. Apply css for width and height. -->
<div id="map"></div>

<script>
    <!-- Create variable "map" -->
	var map;
	<!-- Initiate/render map with this function -->
	function initMap() {
		<!-- Edit latitude and longitude coordinates to focus on a specific region on the map -->
		map = new google.maps.Map(document.getElementById('map'), {
			center: { lat: 35.7932977, lng: -78.6551929 },
			scrollwheel: false,
			zoom: 11
		});			
	}
	<!-- This is the function to add markers for each post. This includes the marker, the information window, and a function to show info when clicked -->
	function addMarker(props) {
		var marker = new google.maps.Marker({
		  position: props.coords,
		  map: map
		});
		var infoWindow = new google.maps.InfoWindow({
			content: props.content
		});
		marker.addListener('click', function() {
			infoWindow.open(map, marker);
		});
	}
</script>

<script>
	<!-- Loop the posts and get their coordinates for the markers -->
	<?php 
	$args = array(  
		'post_type' => 'restaurants',
		'post_status' => 'publish',
		'orderby' => 'date', 
		'order' => 'DESC',
		'posts_per_page' => -1,
	);
	$all_maps_loop = new WP_Query( $args ); ?>

	function renderTheMarkers() {		
	
		<?php if ( $all_maps_loop->have_posts() ) :  while ( $all_maps_loop->have_posts() ) : $all_maps_loop->the_post(); ?>
			<?php if ( have_rows('map') ): while ( have_rows('map') ): the_row(); 
					$map_lat = get_sub_field('latitude'); 
					$map_lng = get_sub_field('longitude'); 
					?>

					addMarker({coords:{lat: <?php echo $map_lat; ?>, lng: <?php echo $map_lng; ?>},
								content:'<?php the_post_thumbnail('thumbnail'); ?><h5><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h5>'});			
				
		<?php endwhile; endif; ?>	
		
	}
</script>
<!-- Your Google Maps API -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>	
<script>
	<!-- Call the function that renders all the markers on the map -->
	jQuery(document).ready(function() {
		renderTheMarkers();
	});
</script>

Here’s what’s happening:

1.) First create/initiate the map using the initMap() function of Google Maps (Line 8). You’ll need a Google Maps API key first from Google to be able to call this function and make use of its other properties (Line 59). This is done in Javascript.

2.) Next is to create a function that generates the marker when coordinates are passed to it as its parameter (Line 17). This is done in JavaScript as well.

This function that we called addMarker() will add the markers on the map and will open a pop up or info window when clicked.

3.) Next is to loop the Restaurants post but in this case we will only get the contents of the Maps field from those posts (Line 31). We will use PHP to create a new query for the loop which will be generated within the renderTheMarkers() JavaScript function.

The loop will create a list of addMarker() functions that takes the latitude and longitude coordinates of each post and uses them for the “position” property for the marker.

We’ve also used a “content” property where the title of the post, its featured image, and permalink are also being called to be added in the info windows.

4.) Last, since all of these looped addMarker() functions are only encapsulated within another parent function called renderTheMarkers() (Line 43), we still need to call that function to finally render all those markers on the map. We called that function on Line 63.

-Advertisement-

Search A Topic

Recent Posts

  • Why Use Python Over R. And Why You Might Not Like R At All.
  • How To Fix “Warning: Creating default object from empty value in…” In WordPress
  • Fix WordPress “Warning: Cannot modify header information – headers already sent by…”
  • Solved: Changing the ‘Publish Date’ does not update post order in WordPress
  • How To Trim Or Shorten The Blank Ending Of The Timeline In DaVinci Resolve
  • Easiest way to redirect your visitors from your old WordPress website to your new. By using 301 Redirect plugins
  • How to export WordPress posts WITH their images and then import them to another website
  • Solved: “The server cannot process the image.” Error in WordPress When Uploading An Image
  • Reaching Out To Influencers For Brand Awareness, Plus A Sample Message Template
  • 3-Step Template To Create A Case Study That Closes Your Leads
©2023 Quedank: Simplify | All Rights Reserved | Privacy Policy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Cookie settingsACCEPT
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT