- Published on
Creating a Crime Data Tool With Google Maps - Part 2
- Authors
- Name
- Justin Kelly
- @JustinHKelly
In this post we get to the fun part of actually creating the map with the Google Maps JavaScript API. All of the source code for this project can be found here. Here is what the final product will look like:
- Initializing the Google Maps Window
- Setting Google Maps Options
- Applying a Custom Map Style From Snazzy Maps
- How to Set Custom Bounds in Google Maps
- How to Add a Search Box to Google Maps Window and Bias Results to Map Area
- How to Add and Remove Google Maps Objects
- How to Customize the Google Maps Info Window
Initializing the Google Maps Window
The code that we will be referring to throughout this post can be found below. The first thing we need to do is to add an event listener that will trigger the initializeMap() function after the page loads (line 1).
Setting Google Maps Options
As part of initializing the map we will set some custom options for our map (lines 7-10). The options we are going to set for this project are to make our map a road map and to remove the option to switch between different map types.
Snazzy Maps
Applying a Custom Map Style FromTo apply the custom styles I just copy and pasted the style object directly from Snazzy Maps and assigned it to the "customStyles" variable (lines 12-116).
How to Set Custom Bounds in Google Maps
By default we want our map to be centered over Baton Rouge. That can be accomplished by setting some custom bounds (lines 118-122). These bounds will need to be adjusted if you are trying to customize this app to your local area. There are plenty of websites available out there that you can use to find the coordinates for a selected area.
How to Add a Search Box to Google Maps Window and Bias Results to Map Area
To add a search box we need to first add an HTML input element to our page and then assign it to a variable. The input element has an id value of "pac-input" and we need to add it to list of map controls (line 126). Next, we need to wrap the input in a SearchBox object (line 128). Finally, we want the search results to favor locations in the current map window. To accomplish this you simply pass the map bounds to the search box "setBounds" function.
How to Add and Remove Google Maps Objects
Next we need to write the code to add & remove map objects. These objects include markers representing individual crimes from our dataset and a circle showing the search radius.
How to Customize the Google Maps Info Window
Todo