When we display Google Maps, especially when we zoom in at local level, we usually want it to center on a certain location on the map so it receives the treatment of prominence. Unless you are displaying the entire world map, zooming and centering appropriately will likely affect the visual impact of the displayed map and its associated information.
Here I have a map displaying all the dog poops littered around the neighborhood. In order to show the users their neighborhoods are getting the attention, the center of the map is the zip code of the registered user. In one of my recent posts, I wrote about how to work with zip codes and GPS coordinates. I will have to assume that when Google API converts zip code into GPS lat and long, it is providing the center of the zip code. Once the user logs in, I can take the registered zip code and use Google API to convert that into GPS coordinates and that goes into my Redux store, which can then be passed into my map component.
On my map component, I set up the local state to handle the different GPS coordinates that may change and affect the map display. “centerGPS” is used for initial map display while recenterGPS is used for subsequent map re-centering (will discuss in a bit).
When the map component is initially loaded or after a refresh, we set the “centerGPS” to the coordinates passed in from the Redux store via the parent component.
When the map is rendered, the center of it is set to the “centerGPS” via the “initialCenter” attribute.
Now my map is centered on the middle of the registered user’s zip code. The beauty of Google Maps is no doubt the ease of navigation on the map. The dragging action allows user to move around, and then, of course, the zooming action which let them see more or less details. However, when the map is dragged around and zoomed in and out, the center will inevitably be moved elsewhere. How do we let users quickly center the map back to where they want?
The “center” attribute of the Map component is the key.
In my map above, I rendered poop markers based on the GPS coordinates of each unpicked-up pile. I passed a handleClick function with the lat and long in the marker’s onClick attribute.
When the user clicks on the marker, the handleClick function set the “recenterGPS” local state, which in turn sets the “center” attribute of the Map component. This quickly allows the user to re-center the map to a particular location on the map without performing the dragging action.