|

Working with Google Maps in WordPress

Working with Google Maps in WordPress in most respects isn’t any different from working with Google Maps in any other platform. There are times however when you will setup data using post meta, or cache data into the WordPress database, or any number of related tasks that are WordPress specific.

Loading the Google Maps Javascript API

The first goals of any new map integration is going to be to get the scripts loaded and a basic version of a map loading. The recommended method of loading the Google Maps Javascript API is to load it with your API key and a callback which looks like this:

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAHaQMa0yE..........[API KEY HIDDEN]..........&callback=initPropertyMap"></script>

In the script loading example above the callback function initPropertyMap() will be called after the script loads. The API key is set so we can expect to be able to load a map without any further authentication (as long as the key is valid).

Rendering a Basic Map

The function to render a basic map is google.maps.Map(). It takes 2 arguments, a DOM element ID where you want the map placed and the map options array.

google.maps.Map( MAP_CONTAINER_ELEMENT, MAP_OPTIONS );

Below is a working example of a minimal set of map options and setting the container element.

var mapOptions = {
  zoom: 10,
  center: new google.maps.LatLng( 46.80421718073698, 7.1371050245889815 ),
};

var mapcontainer = document.getElementById('property-single-map');
const map = new google.maps.Map( mapcontainer, mapOptions );

Use a Custom Map Theme

Google Map styling can be a little bit complicated at first until you get familiarized with it. The style definitions for a custom style are usually setup in JSON code, but they can also be passed an array of settings. Normally we don’t create these styles, instead we find a style we like and download the JSON for it. You can then load the JSON or convert it to a javascript object for loading.

The terminology for what we are creating to customize the map theme is called a “Map Type”. We need to assign a map type ID first in the map options, and this same ID will be used again later when we make the map type so it’s best to set it in a constant.

const mapTypeId = 'properti_map';

Now we use the mapTypeId in our options:

var mapOptions = {
  zoom: 10,
  center: new google.maps.LatLng( 46.80421718073698, 7.1371050245889815 ),
  mapTypeId: mapTypeId
};

Next we’re going to make the StyledMapType. In this example we’re not showing you the long definition of the style, instead we’ll link to that below. Normally we like to store that in a separate JS or JSON file and then load it separately, as long as it’s available before this code that works nicely to keep it out of the way in the file.

const styledMapOptions = {
  name: 'properti_map_style'
};

const customMapType = new google.maps.StyledMapType( propertiMapTheme, styledMapOptions );

google.maps.StyledMapType() takes first the definition of the styles (aka our custom theme) and then an object with options. At minimum we just need to define a “name” which we do here. We now have the StyledMapType stashed into the constant customMapType and we’re ready to do the final step which is to associate it with our map.

map.mapTypes.set( mapTypeId, customMapType );

Notice that we pass mapTypeId as the first argument to map.mapTypes.set(). This is the same ID we used earlier in the map options.

Adding an Infowindow

Infowindows (often called infoboxes also) allow us to show information about the different markers on our map. Right now we only have 1 marker, the primary marker that is sitting at the center point of our map. We’re going to initially setup an infowindow that will work for this marker, but it’s going to be a dynamic infowindow that can later be used for other markers as well.

Key point about managing infowindows is that while you can create a different infowindow for each marker loaded into your map, it’s generally easier to manage 1 dynamic infowindow. The use case where you might need to have different infowindows is when you actually want to allow multiple infowindows to be shown at the same time. Normally we close them on any map click and only one infowindows is open at a time.

const infowindow = new google.maps.InfoWindow();

// Add click handler to close infowindows.
google.maps.event.addListener( map, 'click', () => {
  infowindow.close();
});

With the code above the infowindow exists, but it will never be shown because we don’t have a trigger to open it. We’ll add that next, and this is usually done along with marker setup especially when we’re looping over data creating markers. Although we can try to separate marker creation and infowindow creation, doing so can make our code less efficient.


const content = "This is the infowindow text content.";
google.maps.event.addListener( marker, 'click', () => {

  infowindow.setContent( content );
  infowindow.open( { anchor: marker } );
			
  });

}

In this minimal example above we’re using google.maps.event.addListener to attach a click event listener to a marker. We use the infowindow.setContent() method to set the content. Now in practice this content maybe a much larger amount of HTML that includes an image, title and other text. Real estate maps for instance will often render an image and key details about the listing in the map infowindows.

Adding Multiple Markers

It’s a common requirement that maps display a range of markers. In real estate sites these will often be nearly businesses or attractions to help showcase the location of the property. A store location is another common example where we want to display multiple map markers.

In the spirit of iterating progressively over the work we’re only going to focus on getting multiple markers on the map at this point. Adding the infowindow support will be done in the next section and it just requires a bit of adaption of the code we already we already have in place for an infowindow click event.

const markers = [];
googlePlaces.forEach( ( place ) => {

  let marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
  });

  markers.push(marker);

});

In the example above we are looping over existing data in googlePlaces which is an array of Google Places fetched from the Google Places API. It doesn’t really matter what your data source is here as long as it contains coordinates (latitude/longitude) for display on the map. Usually we want other data that we can use to form the infobox content, or custom icon reference we can use to display a custom icon. In this case we have the most minimal example where the google.maps.Marker() object is created, we pass in the map and the place coordinates which are found in place.geometry.location.

Notice that we initiate a constant “markers” array and then we push each marker object into it. This is an important aspect of managing markers on a map, we need to stash the markers. This later enables us to filter or remove them. You can skip this if your usage is only to render the markers, but if you skip this step note that you also would have to initiate your infowindow click events here instead of having the ability to keep that code separate. In the next step we’ll be looping over this markers array and adding the infowindow event to it.

Similar Posts