Adding zoom level to Advanced Custom Fields maps.

We use Elliot Condon’s Advanced Custom Fields extensively in WordPress at work and I must say, it’s one of my favourite WordPress plugins ever made. That said, sometimes people ask for things that I just can’t work out how to do with the native plugin.

Today a client asked me to allow them to set their own zoom distance on their maps. We’re using the great ACF map field for all the maps so I thought, “Hey, that’s fine, I’ll just go and enable that option”, only to find that there isn’t an option for this. I did some digging around on Google and stumbled across a support thread that asks exactly what I wanted to know.

Whilst there was an answer in the thread, it required me to change the plugin files, something I plain up refuse to do. The last thing I want is for somebody to update their plugins at some time in the future and the whole thing to fall apart. No, I had to find a way of doing this without hacking into any other files.

I came up with the idea that I’ll use a separate field and the client can set their zoom level in there. Whilst that worked fine for me as I know the zoom levels, it wouldn’t be too great for the client, who wants to just be able to zoom in on the map and have that set. After reading through the code samples in the aforementioned support thread, it hit me that I should be able to bind to the zoom_change event in the Google Maps API and then output the value into the second field for use on the front end.

Upon first try, I ran into issues with google not being defined. This was down to the map not being loaded when my javascript was fired. I tried firing my function on window.load() but I still had the same issue. Somehow I had to delay the function until the Google API had loaded.

I ended up doing this by using a setInterval() on a 500ms interval to call a function that checks if typeof google !== 'undefined'. If this returned true, I could then cancel the interval and bind to the maps API. The second problem I ran into, was that I wasn’t sure how to access the ACF maps object. After looking around the ACF plugin file, I worked out that it’s set in js/input.js under the object. I added this to my maps callback and found out that it wasn’t yet defined. This was then added to the previous variable check function and hey presto, it worked. Now it was just a case of linking the fields up, the easy bit.

Below are the files that I used. adminMaps.js handles the heavy lifting and setting of the fields whereas the snippet from my functions.php just makes sure that the JS file is only loaded on post.php in the admin area.

To use this, all you’ll have to change is the selector for the second field, on lines 10 and 18 of adminMaps.js, it’s currently set to #acf-field-zoom_level the ID of my field.

You can also access the full Gist here.

P.S. As a bonus, line 13 of the JS file will disable the scroll to zoom in the admin area!