Auto Center and Zoom with YM4R

When I blogged last month about abstracting mapping with YM4R I commented:

What I’ve not yet discovered (and may not be implemented) is a way to automatically center and zoom a map. It would be very nice to be able to add a batch of points to a map and have the plugin automatically work out their mid-point. Maybe I need to work on that a little…

What I was missing was the center_zoom_on_bounds_init method. There are various ways to interact with it, but I’ve chosen:

sorted_latitudes = locations.collect(&:latitude).compact.sort
sorted_longitudes = locations.collect(&:longitude).compact.sort
  [sorted_latitudes.first, sorted_longitudes.first],
  [sorted_latitudes.last, sorted_longitudes.last]])

That mostly replaces the call to

@map.center_zoom_init([latitude, longitude], 14)

that I was previously using, though I’ve actually kept that around if there’s only one point as I was finding Google Maps’ maximum zoom didn’t show quite enough context for my tastes.

While it would be nice if the plugin had a method that performed the calculations based on the points you’ve fed in, it looks like the current implementation stores the points as javascript strings, so that’s not really an option. But with only three lines of code involved, this is a nice simple way to get the desired effect.

Tags: , , , , ,


  1. Very cool! Worked like a charm.

  2. Excellent! This is just what I was looking for. Thank you for taking the time to post it.