Google map markers from metabox custom post types

The Google map API is fairly easy to work with, and after trying a few map plugins for WordPress, I gave up and used metabox.io to store service area cities to display on a map. If you know of a plugin that accomplishes this and scales responsively and fits the bounds of the map to the markers displayed, please let me know.

Metabox has a map element that really helped in this project. It uses the Google maps API to autocomplete address lookups and return the lat/lng coordinates for the address. I'm using the post title as the tooltip display on the frontend, and the custom fields contain the address and coordinate fields. The code below loops through the service city post types and prepares the array of information to feed to the maps API.

Once the array is formatted correctly, it is JSON encoded and used in the maps API. The official docs explain Google Maps markers in more detail.

Now it easy to add new service cities and this could easily be expanded to include more info in the tooltip popup to make this function similar to a store locator plugin.

By using fitBounds and panToBounds, the map will always be the correct scale and centered for any screen size.

To use this in Oxygen:

  • add both code¬†sections to a code block
  • make sure the maps API key is set
  • make sure you are selecting the right ID here: (document.getElementById('section-map')
  • make sure all post type and custom field IDs match what you have set up in metabox

Good luck!