Working With Google API (Map & Marker)

Dukhyun Ko
Webtips
Published in
4 min readSep 7, 2020
Working With Google API
Photo by henry perks on Unsplash

Even though I’ve been in my coding Bootcamp for only 12 weeks, it feels like it’s been years. The amount of materials that I needed to learn and all the time and effort I’ve put in finally feels like it’s paying off. When I first started boot camp, I didn’t think I’ll be able to become a full-stack developer in 15 weeks, but now that I’m almost at the end of this journey, I’m really proud of what I was able to accomplish and excited about the next step.

When I first used an API (with Ruby haha), it was difficult to even understand where the data was coming from and also how to fetch from the URL. Now, I’m able to use the API provided in the public for my advantage and “try” to be creative with the data. For our React project, my partner and I decided to use Google API. It was a little frightening at first when I looked through the documentation, but after some research, I found out that there are so many different NPM(node package modules) that can help me take full advantage of what Google put out there. Hopefully, the steps I took can help some people like me who use Google API for the first time.

First, get the API Key from Google.

At https://console.developers.google.com/apis navigate to Credentials on the tabs and click on + CREATE CREDENTIALS to receive API Key.

You can use the free API, but there’s also an option to use free trial which is $300 worth of requests for the first 90 days. this gives unlimited access to all Google Cloud Platform.

Let’s code and render the map!

Again, I am using JavaScript and React. Google has so many different libraries, but first I needed to have a map showing up on the Document Object Model(DOM) to work with other libraries. (link for Google Maps).

To render Google Maps I used @react-google-maps/api.

import { GoogleMap, useLoadScript } from '@react-google-maps/api';

After installation, I imported “GoogleMap” and “useLoadScript”.

function Map() {   const {isLoaded, loadError} = useLoadScript({
googleMapsApiKey: process.env.REACT_APP_GOOGLE_KEY
});
const mapRef = React.useRef();
const onMapLoad = React.useCallback((map) => {
mapRef.current = map;
}, []);
if(loadError) return "Error";
if(!isLoaded) return "Maps";
return (
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={10}
onLoad={onMapLoad}
>
</GoogleMap>
)
}

Basically, using useLoadScript, the Map will be loaded on to the DOM if the googleMapsApi Key is valid. And you have to set up width and height to your map to actually have the map show on your page.

const containerStyle = {
width: '400px',
height: '400px'
}; // Use any size you want!

Then I also set up the “center” of my map that will show when I first load the map on to the DOM.

const center = {
lat: 40.7128,
lng: -74.0060,
} // This is New York City
This should be showing on your DOM

Just like that, Google Maps will be loaded. Pretty simple huh? But hold on, try clicking on the map, something is wrong. Google map usually allows us to place markers when we click on a certain location, but our map isn’t able to do that! It is because we didn’t add any onClick event on our map. This part is relatively simple as well thanks to our npm!

Let’s code and render a marker!

import { GoogleMap, useLoadScript, Marker } from '@react-google-maps/api';

Now let’s write up some code to make this work!!

//hook set up mark
const
[markers, setMarkers] = React.useState([]);
//function that will run when you click
//if you want more than one marker, u can always use spread operator in setMarkers.
const onMapClick = React.useCallback((event) => {
setMarkers(() => [{
lat: event.latLng.lat(),
lng: event.latLng.lng(),
time: new Date()
}]);
}, []);
//Update your GoogleMap<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={10}
onClick={onMapClick}
onLoad={onMapLoad}
>
{markers.map((marker) => (
<Marker
key={marker.time.toISOString()}
position={{lat: marker.lat, lng: marker.lng}}
>
</Marker>
))}
</GoogleMap>

event.latLng.lat() and lng: event.latLng.lng() in our onMapClick is able to locate and set values of latitude and longitude for your marker. I put in time so that I can put a unique key for each Marker. You can style your marker by adding an icon into your Marker component, and also add an onClick event on to the marker.

This should be showing on your DOM
<Marker
key={marker.time.toISOString()}
position={{lat: marker.lat, lng: marker.lng}}
icon={{
url:IMAGE YOU WANT,
scaledSize: new window.google.maps.Size(50,50),
origin: new window.google.maps.Point(0,0),
anchor: new window.google.maps.Point(25,25),
}}
>
</Marker>

Following these steps will allow you to render a map on the DOM and whenever you click a location on the map, it will use its latitude and longitude to place a marker on the map. You will need to use other Google API such as Places, Directions, Routes to add other functions to your app. Hopefully, I can write another blog post about those API.

If you are still struggling to have a map show up on the page follow this youtube guide https://www.youtube.com/channel/UCWPY8W-FAZ2HdDiJp2RC_sQ. He tells you everything you need to know.

Pricing Information to use Google Maps:
https://cloud.google.com/maps-platform/pricing

--

--

Dukhyun Ko
Webtips
Writer for

Software Engineer 👨🏻‍💻 | Personal Trainer 🏋🏻‍♂️ | Commissioner 🏀