Sunday, 21 September 2014

Quickly Finding the Center Point and Zoom Level in Google Maps

When I'm putting together Google Maps API applications for demos or classroom exercises, I often start off zoomed into a particular location to spare students the pain of watching my clumsy efforts to find the area I'm interested in.

I've got a couple of methods I use to grab the current zoom level and lat/lng of the center point. I can then put these into a mapOptions object and have the map position itself to this location automatically when the page loads.

Method number one is a little app I wrote specifically for this purpose. You can see it above and access it here.

Just zoom to the extent you want to set your map at and press the "Create MapOptions for this Location" button.

You'll be presented with a dialog box, which formats the current location into a mapOptions object ready for pasting into your app.

There's another way of getting this information though, just by using a little bit of code in your browser console. But be warned: it only works when the variable you use for the map object is global and actually called "map".

Here's the code:
 (function() {console.log("Lat:" + map.getCenter().lat().toFixed(3) + ", Lng:" + map.getCenter().lng().toFixed(3) + " Zoom Level:" + map.getZoom() );})();  

It's pretty ugly, but it does the job. Basically, this is just a self-executing function that calls getter functions on the global map variable, and outputs the display to the console:

Paste code into console and click Run
I don't want to type this out every time I use it, so I have got it configured as a keyboard shortcut using Autohotkey. (If you're on Windows and you haven't checked out AutoHotKey yet, you're doing yourself a disservice. AutoHotKey lets you automate just about any Windows task, from text expansion to changing display resolution, and I'm lost on any machine where my AutoHotKey scripts are not installed.) 

AutoHotKey Script
 :*:@@map::  
 (  
 (function() {console.log("Lat:" + map.getCenter().lat().toFixed(5) + ", Lng:" + map.getCenter().lng().toFixed(5) + " Zoom Level:" + map.getZoom() );})();  
 )  

Without delving into the syntax, this means that every time I type @@map (I had to suspend the script just to type that!), the function executes and returns the map details.

I find these methods useful on an almost daily basis. I hope you get as much mileage out of them as I do! What are your favourite Google Maps API tips?

No comments:

Post a Comment