Getting started with Google Maps is a walk in the park if you have the right tools. Firstly, you will need to add the Google Maps Geocoding API to your project. You can obtain an API key here:
Geocoding is the process of converting addresses (like a street address) into geographic coordinates (like latitude and longitude), which you can use to place markers on a map, or position the map. To obtain your desired coordinates, first you will need to create a simple search bar with an event listener. You'll want the event listener to fire off a function similar to the following:
Here, we are taking the string of what the user entered into the search bar and replacing any spaces that would exist between words with plus signs. This is done to format the search term in a way that will allow you to interpolate it directly into the url. With a bit if digging, you can extract latitude longitude coordinates out of the json object that this API call will result in.
Well, great! What's next, you might ask? To render the map itself, we can use the initial results from out search to center the map around our first lat-lng coordinates. Firstly, we will have to create the div tag where our map will live.
We add the ID "map" here so that we can target this div to populate it with our map, as such:
Here, we create the new map centered on the lat-lng coordinates we received from our prior search, set at a default zoom of 9. If we were to center our map on Seattle, WA, we would expect to see a result that looked like this:
From this point, it's a small step to populating your map with markers. Utilizing our prior search method, we can obtain a set of geocoded coordinates and store them into an array. We can pass this array of markers into the function below to populate our map with markers.
This function is doing a few things. Firstly, we iterate through our markers array to create a marker at each geo coordinate saved under the 'position' property. We also designate the map to which we are adding the markers. For a bit of added flair, you can set custom animations, titles, and images to your markers. In this case, each of my markers will look like a camping tent and will drop from the top of the map when populated. The name of the location will also appear as a tool tip on the map if you hover over it with your mouse.
And there you have it! Using these methods, you can start venturing into creating maps to polish up any application that could make use of them.