Factor out some code to a separate function for better profiling

Need to rule out the reason for unexpectedly slow profiling results for
{{#coordinates}} in production - if the new function takes the majority
of time, it's just because people feed complex wikitext into it.

Change-Id: Ibb5312973316b0d8348c2bb2cfa9fcb6702250e7