How to use Google Maps API with React including Directions and Places autocomplete

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay guys so welcome back again so in this video we'll be doing a quick tutorial on google maps api using react.js and here we would be displaying the google maps here inside our window here that is in the full screen mode and then we will be also seeing that how do we get the directions renderer to render the directions from origin to destination and we would also see that how do we get the total distance in total duration of that and you would also learn that how to add markers to your google maps so this is the demo of the application so currently we have a map here that is centered on eye filter and we see a marker here so if we drag the map and if we click this button back again so we see that we are panning back to the center again so if we click on the origin and if we simply type here eiffel tower and the destination would be let's say paris that is that may be the center of paris and if i click here that is calculate route then we see a route is displayed between point a that is origin and point b that is destination and we have a total distance here and the total duration here and if we choose the origin to be apple park and the destination to be google amphitheater then our map would move to that location and we would be seeing the directions here so that's what we are going to do in this video so for this video what i've done is this that i've created a very basic react application which you can download here on this repo here that is this github link and there you can select the branch that is called startup branch to code along with me and then inside the react application or the react package that i created using the create react app what i've done is that that i've stripped down all the css files here and the only files remain here are the index.js file and the app.js file and for this application what i've done is that i'm using chakra ui though you can use any ui library you want or you can use the plain old html in css but since it's not a video about ui i would be focusing on the google maps api and one more thing that i have done inside this project that is this react project i've installed this dependency called react google maps forward slash api so if we have a look at this npm package here on the browser we see that this is the actual package you need to install though there are a couple of different npm packages that you can install but i would recommend you using this package because like it provides you with great functionality for the direction service also and for the directions renderer also so that you do not have to worry about other packages because all the google maps apis are built into the single package and we would be seeing that at how to use this so for this project what you need to do you need to create a new project on google cloud platform and if you already don't have a project on google cloud platform then you can create one it's super simple to do and then you need to go inside this tab here that is apis and services and here we wouldn't be needing to enable the google maps api so let's click here that is enable google maps api and services and here i would be simply selecting this maps javascript api so let's select this maps javascript api and let's click on enable here and it would enable a couple of things that is the maps api as well as the directions api and the places api because we would be using the places autocomplete feature also so it might take a couple of seconds or more to enable this api so we see that this maps javascript api has been enabled and we might also need to enable this directions api as well as this places api because we are going to use the places auto complete feature so let's click on directions api and we need to enable this also so let's enable this also and then we need to enable one more api that is the places api and that's all what we need to do inside this enabling apis thing because we have all the three apis necessary for our application and enabled here so now what i'll do i'll go to this maps platform or i'll click here and here what i need to do i need to go inside this apis and services tab once more and here i need to click on credentials to create our api key for this google maps thing so here what i'll do i'll simply click on create credentials select click let's click here create credentials and here i would be selecting the api key and it would be creating an api key in a moment so let me copy this key and don't and don't take time to use this api key because the time you will be watching this video this key would have already been deleted so let's close this and now what i'll do i'll go to this api key to bit which has been generated i'll rename this key to google maps api key simply like this and if you want to restrict this key to use a particular service then you can click here and you can restrict it by selecting the type of apis you want to use but for this demonstration i am not restricting this api key so let's click on save here and let me copy the key here once again so let's click on show key and let me copy this key here so let me copy it to my clipboard and let me close here and that's all what you need to do inside the google cloud platform so let's go back to our application and here the dot env dot local file what i've done i have done created a environment variable by the name of react app because we need to expose this variable to the client side so therefore i have prepended it with react app and then the value of this variable would be this thing here that is the key from the api from the google cloud console so let me copy this environment variable in my clipboard and let's save this and if i start this application by doing yarn start or if you are using you can simply do npm start but i'm using yarn here and let me minimize the terminal so that the application is always started in the background so this is what you see when you start the application so let's go back to our application let me minimize the terminal so let's go to our js file and firstly what i'll do i'll simply remove the background image and the background position because they were only for styling purposes so now we are at this stage here that is the background is removed and now what i want to do is that that i want to display the map in the full screen window that is hundred percent of the viewport with 100 of the viewport height so what i'll do i'll go back and here we have the basic ui ready and inside this box that is inside this box i'm going to display my google maps so google map box and as you can see that it has a position of absolute in its parent and it has a height of hundred percent width of hundred percent and the parent has a height of hundred percent viewport with a report height and a hundred percent viewport with so this is where we are going to render our google maps so that it takes the full height of the container so before doing so what i need to do i need to use a couple of things from the package that we installed or was provisions previously installed that is react google maps api what i need to do i need to import a couple of things from that package so import something from uh at react google maps api and what we need to import first is the usgs api loader so let me import this thing here that is use js api loader and basically this is a hook which provides us with the with a variable called is loaded whether the map script is loaded on the browser or not so let's save this and to use this uh hook what we need to do we need to go inside our app.js file and here we can use this hook that is caused something equal to use js api loader and here it takes an object where we simply need to provide in the google maps api key and the google maps api key can be read from the environment variable that is this environment variable let me copy it again so let's copy this and let's paste it here like this and this returns us over the is loaded variable whether the map script is loaded or not and inside a typical html uh application you will be pasting in the script for the google maps but that is what this script or this hook is actually doing it is simply loading the google script from the cdn to be used inside our application so firstly we will check that is if not loaded then what we want to do we want to simply display a skeleton or something like that that the maps if map service is loading or something like that so for that i'm going to use a chakra ui thing that is to display a skeleton here that is some loading is in progress so if we save this application and if i simply and we need to return this not like this so it should be return like this so if i simply remove this exclamation here that is if the map is loaded then we would be seeing this skeleton text here so if i save this application and let's go back so we see that we have a loading skeleton here which means that the api key has been loaded inside our application so this should be this not if is loaded that is if the script is not loaded or till the script is loaded we want to simply return something here or you can simply display loading here but i'm simply displaying a skeleton object here so let's save this and now once this map is this this is loaded is true which means that we come here that is inside this return block then we can simply display our google map inside this box so to display our google map what we need to do we need to import one more thing from here that is google map from this uh package again so let's save this and for this application what i'm going to use i'm going to or let me write it first so google map inside this box here so google map like this and here we need to do a couple of more things like displaying markers or directions like this so that's what we are going to do inside this google maps thing here and this google maps takes in a couple of things firstly we need to provide in the center for the map that is where the map should be centered so for that what i'm going to do i'm going to copy one center object from here and i'm going to paste it here at outside this app.js file or inside this functional component so the center would be the center here and this is basically the center of eiffel tower so let me copy the center here so the google map should be centered on this eiffel tower so let me pass in center here and then we need to provide in the zoom level that is how much it should be zoomed to so let's provide in a zoom level of 15 and then if we save this we would see that we don't see the map here and that is because we need to provide this map container a style that is to provide the view box to this google maps so for that what i can do i can simply provide an map container style and here i can simply give it a width of 100 so 100 percent that is the 100 of the parent and height of again hundred percent uh like this so let's save this and uh if we go back to our browser we see that our google maps has been loaded and we see that we are getting this error here that is for development purposes only and this is because i have not enabled billing in my google project here so if we have a look at the console here we see that we get a message here that says that we need to enable billing for this google cloud project so which i am not going to do so but for tutorial purposes i am simply going to use a different api key so let me do that in a moment so as soon as i used a different api key we see that our google maps has been loaded here and we need to fix the z index of this ui element and that is very easy to fix so we need to simply go to this box here and we need to give it a z index of let's say model and this is all chakra ui thing you don't need to worry about this thing here and now we see that we have a google maps displayed inside our application and now if you want to configure that you want to see this maps and satellite buttons and so on and so forth so that is very easy to fix so if i click here to terrain then our maps should be load oh we can see the terrain here and if i click here satellite we see that our satellite map is displayed here so let's remove this thing here and let's remove also terrain here and now if you want to go into full screen you can simply click this button and now we are inside the full screen mode and now let's go back and now we have these buttons here that is the zoom level control buttons and the street view thing here that is this kid here so if you want to disable this controls here that is this map satellite and this uh full screen and this baby here and these zoom controls what you can do you can go to our your google map here and here you can pass in some options here so let me pass in some options here like this and here i can simply say zoom control to be false like this a street view to be a street view control to be false and then map type control to be false and full screen control to be false and let's save this and we see that all the controls are disabled here that is we do not see a map type option here we don't do not see a full screen control and that street view baby here and the zoom controls here so now what you want to do here is this that we want to display a marker on the center here that is on i filter so how do we do that that is pretty simple to do so let's go to this uh package here that is the import statement from this package and here we need to import one more thing and that is the marker object or the marker component so let's import this marker component and let's scroll down and here inside this google maps component what i'll do i'll simply display the marker component here like this and this and the only required drop to this marker component is the position attribute or the sp or the position drop here and for the position i can simply pass in center here again because that is where we want to center the marker so let's save this and if we go back we see that we have a marker here at the eiffel tower itself so this is how easy it is to add marker to this position and in a similar way you can add as many markers to this google maps component as and as you want it is not only limited to one marker so you can add hundreds of markers here like this so it would work the in the same way but all the 10 markers is added on the same position so that's why we are only seeing the single marker because the position for each of the markers is same so let's go back and let's remove the extra markers from here and now what we want to do is this that let's save this application and what we want to do is this that if i drag this map and if you want to go back to the center here that is this eiffel tower i want to click on this button here that is the icon button here which we see so as soon as we click this button currently it is displaying us as an alert but what we want to do we want to pan the map back to the center so to do that it is pretty simple to do so let's go back so for that what i need to do i need to create a state object or a state variable for google maps to control the map which is loaded from this google maps component so for that what i'll do i'll create a state variable here at the very top of our application and here i will simply say use a state like this and here i would simply say it map and the initial state would be null that is initially the map would be null because no map might be loaded and we need to import user state from react so we have already done this here and now i would show you a trick that is how to get auto completions on this map state variable in a moment but first let's use the setmap function here to set the maps to this state variable map so inside this google map component we have a callback here that is on load event and here what we can do here we have the map here because as we see that this on load map on load function uh provides us with the map objects and so we can save map like this and then what we want to do we want to simply set the map to this map that is coming inside this onload event so let's save it and now what we want to do inside this button that is this button that say that is uh that is this button here let me see where it is so this is this button here that is uh that is displaying as an alert of one two three which we already saw in a moment so what we want to do we want to simply pan the map back to the center so what we can do we can use the map object here that is the map or the map state variable dot pan two and we see that we do not get any autocompletion for this map here so a basic trick to use types inside your javascript files is to use js docs so it is pretty simple to do what we can do instead of providing null like this we can provide in the type of variable this map is so what we can do we can simply define the type for this map variable like this that is forward slash star star and then it ends with a single star and forward slash and here we can simply say add type like this and the type would be google dot maps dot google map simply like this and this null what should be inside its own braces here like this and this should not be google map it should be map like this and let's save this and if we go here to this on click event and now if we remove this thing here what we can do we can simply use map dot pan 2 and we see that we are getting all the auto completions that are provided by the google maps thing so we have the map object here so we can simply use map dot pan two so if we simply use uh set center it will set the center of the map to the center uh uh to the center which you are going to provide otherwise we can use span 2 which simply slowly drags on the map map or it animates the map so it is better to use span 2. so pan 2 and here we need to provide in the center that is the lat lung object so basically this center is a lat long object here that is it has a latitude and it has a longitude so that's all what we need to do so if we save this and if we go back to our application so let's see we scrolled here and if we click here that is on this button so we see that the map has spanned back to this center here so if we scroll here we should be spanning to this center here so this is how easy it is to use uh this panning thing on the map and now let's have a look at how do we use the places auto complete api inside our application or inside our input elements that is as soon as we type here we want to get auto completions from google so that we can select select those options so for that what we need to do we need to go back to our application and inside this thing here that is inside this user js api loader we need to provide in one more thing here and that is the libraries that is what all libraries do we want to use and this is an array here and we want we can use here a couple of different libraries but we are interested into using uh use the places api so i am simply going to select this places thing here that is when the google maps script loads we also want that script to enable places api so that's what we are doing here so let's save this and now to have auto completion in inside our input boxes what we can do we can use one more component from this react package or this react google map package and that is the auto complete component so auto autocomplete like this and then the only thing we need to do inside our app inside our input components to get auto completions we need to simply wrap our input components because these are our two input components that are rendered here that is uh let's refresh it that is this input component that is origin and this destination so the only thing you need to do is that that you only need to wrap your input component with this autocomplete component so here i would simply do autocomplete like this and then i would simply wrap this input component inside this autocomplete component and the same thing i am going to do for this input component that is for the destination input component and i'm going to wrap the input component for the destination to be auto wrapped with this autocomplete component so as soon as we save this and if we go back to our application we would see the magic happening here so as soon as i type eiffel tower we see that we have an autocomplete box here with that is powered by google and we can select here anything we would like to have so let's select here eiffel tower and we see that we have this eiffel tower here and similarly for the destination if we provide in paris here we see that we have auto completed places auto complete feature enabled inside our application that is again powered by google and if you wanted to use this component by your own that is you want to display this places rendering according to your ui design then you need to do a couple of more things but this is how i would keep it for this video that is we see a select option powered by google here so let's select france here and now what we want to do we want to calculate the route whenever the these two input boxes are filled with the places uh autocomplete so i want to click here that is calculated that is calculate route and i want to display that route over this map and i also want to display the distance here and the duration here so for that i need to do a couple of things inside our application so firstly let's create a couple of more variables here or a couple of more references here so here we need to create one more state variable and that is the directions response that is whatever directions response we are getting back whenever we are calling the directions apis so let me use the user state snippet once more so use a state and we would be calling it directions response that it that is whatever response we are getting when we are calling the directions api and the initial state would be null like this and then we need to create a couple of more state variables that is the distance and the duration so use a state so distance and initially it would be an empty string and then use a state once again so it would be duration initially it would be an empty string and then we need to create a couple of refs for our input elements i'm not using user state variables for the input elements but i'm using refs here so i would simply say const origin ref would be equal to use ref like this and similarly we we would be having a destination drift so destination riff would be equal to use ref once again like this and again what i'm going to do i'm going to create a type for this riff object so that we have we have better auto completions in vs code so the type of this ref of this origin ref or this input element riff would be this html input element riff like this and you can copy the types here from my repo also and this is only for better auto completion inside vs code so now we have defined the origin ref and the destination ref and let me provide in these riffs to our input elements so let me provide in a ref here so ref would be origin ref like this and for the destination drift let me provide another key so this would be called destination riff simply like this and this is all what you need to do for this thing to work so let's save this and now what i'm going to do i'm going to create a function here that would calculate the route so i would create a function here that says calculate route root if you call it that way and when do we want to call that function whenever the input element is not empty so we would check that if origin ref dot current dot value is equal equal to empty string or destination ref dot current dot value equal to an empty string then what do we want to do we want to simply return here that is we do not want to proceed ahead in this function otherwise what we need to do we need to create an object of this direction service from the loaded script though there is one more thing inside this uh this package that is direction service provided by this package itself that is react google map cpi but that is a bit typical to use and that is not recommended because it's too complicated to use so therefore i am going to use the plain plain javascript version of that direction service so i would simply say const directions service equal to new google dot maps dot direction service like this and then it gives us an error but that is not an error because the maps script is already loaded so i would simply disable this new undefined for this line that is i would simply disable the eslinting which we are getting here and now what we want to do we want to call this direction service to get the results so we can say const results equal to await direction service dot route and here we need to pass in an object containing the origin so origin would be simply origin ref dot current dot value that is the value inside the input element and we need to also provide in the destination and here we can simply say destination ref dot current dot value and then we need to provide in one more thing that is the travel mode that is uh to get the directions of the travel mode and here we have a couple of directions here but i am simply going to use in the travel mode with driving directions so google dot maps dot travel mode dot uh not transit mode but travel mode so travel mode dot driving like this so this is what i'm going to use here and now since we are using a weight here because this route returns as a promise so if we hover over this we see that it returns as a promise that gives us direction results so since we are using a weight here so we need to make this function as async like this and now the error is gone and again this is uh like uh squeaking at us that we have google is not defined that is name space google is not defined so let's remove that with eslint here that is no undefined for this line and now what we can do whenever we get back the results so what we can do we can simply set the directions respond to this result so set directions response to this results thing here and then we can do one more thing that is if we or let me log in the results here or let me do it directly so set distance so we can get the distance from the routes thing here that is results dot routes and we want to call in the zeroth route because uh that there can be several directions from one place to another so we are using the only the first direction so directions dot routes legs and then again we target the zeroth element and then we get the distance here and dot text and if you use the value thing here so distance dot value would simply return you the distance in meters so i'm using the text here that is the human readable value whether it's in kilometers or it's in meters and it would be depending on the locale of the application where it is used and here for the duration i would simply using the same thing here let me copy it like this and here i would simply say set duration would be not distance or text but duration dot text simply like this and again if you were using the direction or duration.value then this value would be in seconds and then you can display it according to your choice but i'm simply calling it like this and now we also want to have a function that can clear this route so function clear route it's a super simple function that is if someone clicks on this button here that is this times icon or this times button then the route should be cleared from the map as well as this input field should be set to an empty string so that is pretty simple to do so here we can simply say set directions response to be null again set distance to be an empty string set duration to be an empty string and then origin ref dot current dot value would be an empty string and the same goes for the destination riff that is for the destination element and now when do we want to call these functions that is calculate route and this clear route it is it should be called on these two buttons that is the calculate route button here uh that is this calculate route button so let's call that function here so on click should be calculate route and for this for this button instead of displaying an alert it should be clear route simply like this and now if we have a look at our google maps here and if we type here anything we have only set the directions inside this direction response object here or this state variable here that is this state variable so where it is so to this state variable but we have not rendered these directions on the map so for that what we need to do we need to import one more component from this google maps api package and that is called directions renderer like this and now when do we want to display the directions render inside our google map so let me remove this thing from here so we only want to display the directions renderer inside our map only when do we have directions response so if we check that if we have directions response then only we want to display our directions renderer simply like this and now this directions renderer takes in a couple of props here so and the props would be directions would be directions response so directions response and that's all what you need to do so let's save this and let's see that in action so currently we see that we have this map here so let me type here eiffel tower like this and let me choose the destination to be paris like this and as soon as i click calculate route let's see what happens so let me click here so we see that we got a route here that is point a would be your origin and point b would be your destination and we see that we have a route here and in the same way you can calculate the route from apple park in cupertino to let's say google amphitheater so let's calculate the route and our map will be moved to that location so let's calculate the route and before calculating route we see that we do not see the distance and duration here and that is because we have not displayed these state variables that is distance and duration anywhere so let's display them also so inside this uh this uh this text here we can say distance like this and for the duration let me pass in the duration like this so let's save this and let's try to calculate the thing here that is this calculate route so let's calculate the route here so we see that our route has been calculated from point a to point b and this time the distance is in miles and the duration is in minutes and if we were in europe the distance was in kilometers if i'm not wrong so we can click here that is to clear the routes so let's click here that is clear the route and the route is cleared from the map and if you want we can go back to our map center here that is this center here like this and again if you want to calculate the route so let me click on paris france and let's go to eiffel tower this time so eiffel tower paris france so let's calculate the route and this time we see that we again have a route here and the distance is displayed in kilometers and duration is 18 minutes and again if we want we can clear the route so this is how easy it is to integrate google maps inside your react application so guys that's all about this video so if you have liked the video do hit the like button and if you haven't subscribed to our channel do subscribe to our channel so thank you bye tada take care and have a good day and have a great day
Info
Channel: Mafia Codes
Views: 103,127
Rating: undefined out of 5
Keywords: yourstruly, how to use google maps inside a react application, how to get directions from google maps, places autocomplete google maps, google maps directions api
Id: iP3DnhCUIsE
Channel Id: undefined
Length: 32min 50sec (1970 seconds)
Published: Mon Mar 14 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.