After a long pause, I am back to my Google Maps application. In other words, the 3rd video of the series is out! In this video, our Google Maps application turns out to be something useful. The application lets the user calculate distance between some points on the map. Below is the list of tasks completed in part 3:

  • Create home address marker with center and zoom functionality (panTo and setZoom)
  • Calculate distance between home address marker and custom markers (computeDistanceBetween)
  • Draw a line between home and selected marker (polyline)

Github URL: https://github.com/SercanSercan/youtubeStuff/tree/master/google-maps

This article will point out some of the critical code snippets in the video. I prefer to make up some questions that you may ask along the way.

1. How to create markers with PNG files?

You don’t have to use SVG content to create markers in Google Maps. In some cases, you may prefer to use PNG instead. For example, while creating the home marker of my application, I used a PNG file. Place the image into some folder that is located under your public folder (such as public/assets/images/…) and the icon attribute of your google.maps.Marker constructor receives the url parameter as shown below.

const homeMarkerConst:GoogleMarker = new google.maps.Marker({
    position: location,
    map: map,
    icon: {
        url: window.location.origin + '/assets/images/homeAddressMarker.png'
    }
});

2. How to create an event for a marker in Google Maps?

You can implement some operations on markers via adding event listeners on them. Preferably, you should add your event listener and the corresponding function right after you create the marker. The code snippet below shows the event listener that I added to my home marker. The arrow function changes the center point of the map with the location of home marker.

homeMarkerConst.addListener('click', () => {
    map?.panTo(location);
    map?.setZoom(12);
});

The gif animation below shows how this listener performs in the application. After the user clicks on home marker, the map centers and sets the zoom level to 12.

Homework! 👀

As you see, my zoom operation in the code snippet above is not actually smooth. Clone my repository and create a function called smoothZoom. This function should zoom gradually. I want you to change the zoom level in every 100 milliseconds. (💁 Hint: smoothZoom should be recursive)

3. How to compute distance between two markers in Google Maps?

We so far learnt how to perform some function when a marker is clicked, right? So, if I should calculate the distance when a marker is clicked, what am I supposed to do? The answer is adding another click event listener. Before that, you should add another library to your Api URL. If you’d like to calculate distance in Google Maps, you should use the function computeDistanceBetween(…, …). This function lies under geometry library of Google Maps library. Therefore, your Api URL should be something like this:

maps.googleapis.com/maps/api/js?key=${your_key}&libraries=geometry,places&language=no...

After making sure that libraries have geometry, now I can add the click event listener which gets the position of two markers and computes the distance between them.

marker.addListener('click', () => {
    const homePos = homeMarker?.getPosition();
    const markerPos = marker.getPosition();
    if (homePos && markerPos) {
        const distanceInMeters = google.maps.geometry.spherical.computeDistanceBetween(homePos, markerPos);
        console.log(distanceInMeters);
    }
});

After adding polyline code and few more other things, the code above helped me measure the distance between home marker and custom markers as the gif below shows:

4. How to use React Hooks inside marker event listener?

This is the most challenging part while implementing Google Maps with React. The event listeners are part of vanilla javascript and they have no respect against the render mechanism of React. They only remember the hook values of the moment that you added the listener. Therefore, when you try to perform some setter operation of a hook, its value will not always be updated. I mean the hook value will actually be updated, but your listener functions may still remember the former value of the hook. (I know! This part is a bit complex. So, read this paragraph again and ponder)

To fix this, you should remove your listener function and add it again. So that, your new listener event will keep the updated version of your hook value. Therefore, I keep the listener ids of my events in a hook array and whenever I am supposed to update some hook value inside the event listener, I remove all previous listeners and add them again. I won’t share a code snippet for this part, so you’d better watch the last 20 minutes of the video 😁

Hopefully this blog post will help someone in the future! And again hopefully I will make the 4th video some time soon.

Sercan Leylek

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s