Building an interactive map with Google Maps Platform and React - Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey i'm lee holliday and i've partnered with google and the google maps team to create a google maps and react crash course where we're going to be going from basically nothing all the way into a really cool experience with google places directions marker clustering and here's what we're going to be building so we'll start off with basically an empty map and a google places search box where you can search for your office so let's say that we work at the google kitchener office it's going to place a beach flag marker on the map and it will draw some concentric circles around the office sort of green is easy to commute to yellow you could but it's starting to get far away and red is pretty far at this point at the same time we we show some markers and we cluster them together and that allows us to click into one and choose one of the houses we may buy and as soon as we choose a house it draws directions from our potential house to our office and on the left it shows us this is 57 kilometers away and it will take 45 minutes to commute each way but if you were to do that over the course of a full year the average american works 260 days a year so if you were to multiply that out that's actually 16 days you'd spend in your car and it would cost you over 4 000 so this is what we're going to be building over the next hour the first thing we have to do to even get started with showing a map on the screen is load the google maps script so we're going to do that right in the home component that's being rendered inside of next.js inside of the pages index file we're going to use the you use load script hook that comes with react google maps api the package that we're using to display the map so what we're going to do is we're going to say const and it gives us something back boolean called is loaded and that will let us know when the map is actually ready to display so for this we can call the use load script function and to that we need to pass two things the first thing is the actual google maps api key so for this we're going to have to hop over into our browser and if we go to the google cloud platform where you can manage all of your credentials and things like that you can click create credentials api key and this will generate you a new api key that you can copy keep in mind that you should go and restrict it to whatever domain that you're hosting this website on otherwise anyone who found the key could go and use your api key so we don't want that so we'll come back here and if we paste this in yes it will work but you shouldn't do that you should try to avoid committing any sort of key anything that's potentially confidential into your actual code because if you're putting this on github that would expose the key pretty easily to anyone who's looking so instead what you would do is you would take this key and you would go into at least locally in xjs the dot end dot local file so i already have another api key i'll just copy it over it doesn't really matter here and keep in mind you should have next underscore public underscore prefixing the name of this key otherwise next gs won't expose it into the the client-side javascript that it's that it's creating so we can come here and we can replace this with process dot end and then the name of our api key the next thing we want to do is uh tell it which libraries were we're hoping to use with this google maps script that we're loading so for that we'll say libraries and we're just going to pass in one extra places so places we don't need to actually show the map but we are going to be working with google places to find our office and uh so we might as well tell the script that we need this now so the last thing i want to show is that once we've set up our key and all of that you need to make sure that you've enabled the apis that we're going to be using in this tutorial so the four that we're working with first of all it's the maps javascript api that's just to use the map itself we need places api for the google places search geocoding because once we get sort of the address from here we're going to use the geocoding api to convert that string into latitude and longitude and lastly directions api because we're going to be asking for directions between two sets of coordinates so these are the four apis that you need to enable so coming back here you can see the only thing we're showing right now is just the word map so we're going to be working on that in a second but first we're going to check has this script finished loading so we're going to say if not is loaded so it's not done loading yet here you can show whatever loading screen you want we're going to keep things simple for this tutorial and just say loading dot dot dot and it will show that for a split second so if we load this it's so fast you can almost not even see it and when it's done loading we'll just return out a div that says map so that's the first part we've loaded the actual script now let's move on to rendering out the first version of our map so i'm rendering out a div that just says the word map obviously we can't stick with that so instead what we're going to do is we're going to render out this map component that i'm importing from components map so we're going to go and put the actual logic of our map here and we're doing this just so that as we're building this this app we don't end up with just one massive file with a bunch of different components and we're just splitting up our code into smaller pieces so if we open this map file there are there is some code here already let me quickly explain what's going on i've set up the imports that we're going to be using just to save some time as we're going through the tutorial it's more about i want to show like how to use these imports and then as we use each one we'll talk about where they come from we're also working in typescript so i've pre-set up some sort of shortcuts so whenever i want to use the lat long literal i don't have to type out google.maps.lat long literal the actual component that we're working with itself actually just renders out a div that says map for now so here's where we'll be working and i've set up some options below for displaying some circles that we'll be showing that shows us sort of like an easily commutable distance potentially commutable very difficult to commute from it sort of goes in concentric circles out adding more distance each one so lastly i've got a little function to generate some houses to display on the map we'll go over this when we get to the part of showing these houses it's just basically randomizing some houses to display on this map so back to actually rendering out the map what we're going to do is we're going to start with just setting up this div here with a class of a container so class name container what does this container do it's in here my global css it just sets up flex height of the whole screen the v100vh so within the container we're going to put two other divs the first div is for the controls so we'll give it a class name of controls and this is where we're going to put our google places search for now we can just put an h1 that says commute question mark so if we were to come here now we're starting to see this take shape we got the controls over here on the left the map is going to show up over here on the right so we can go create another div here and we'll give it a class name of map and if we look at the css from that the mat the controls is just 20 width some colors the map is 80 percent width and sort of forcing it this 100 vh so we can come back here and inside of this div is where we're going to use the first component to display the map this google map component right here so we'll put this in and we need to give this a few props for it to even work if you just look right now nothing's showing up so that's a tip to us we need to do something to make it work a couple things we need to give it first what level of zoom will this be sort of defaulted to when the the user loads the map for the first time on the page next is where should the map be centered on and yes we could come here and just hard code the latitude and longitude that we're going to be using for the center but that can cause some issues where every time this re-renders it thinks this is actually a new set of coordinates so if we put in lat 43 lng of 80 minus 80 actually this would render out fine the first time but sort of every time it re-renders this map component uh google map component is going to think oh you want me to re-center this map at this new location sure i can do that and it will sort of plop it back to the center even if your user has dragged it around so to get around that we need to basically use the same instance of the object every time so we'll take this and one way you can do that is by putting it out here sort of outside of the component itself center that would work another way you can do it and the way we'll do for this tutorial is to put it inside of here but to use the use memo hook so basically this tells react go and generate the value once and then reuse that value unless one of these dependencies change the second argument here but because we're not passing any dependencies it'll never change so you'll always get the exact same reference to this object right here that was returned from the arrow function so is the map showing up not yet but we're almost there so the last thing we need to do is basically just set the map container this sort of what space should this map be rendered into and for that we can give it a class name so map container class name and we'll give it one called map container and map container is just 100 width of this 80 width div and 100 vh so if we come back here you can see we have the map rendering for the first time we can drag it around we can do whatever we want um and last thing we're going to do is basically just tweak a few options of this map um in this case you can switch to to satellite or to map you can switch to street view if i want just like a more simplified view of the map i can set up some options to have it not render these out so for that i'm going to follow the same sort of approach here where i set up options with use memo like that no dependencies just an empty array and the options that i'm going to be working with are to disable the default ui true and clickable icons false so just different icons that may show up on the map as you zoom in like dragons golf clubs and parks and stuff like that we don't want the user to be able to click these in our case so we can just disable them by passing this in so once i have the option set up i can come back down to the map and i can set the options to be options cool so you can see it removed these um default controls i i got out the the zoom here and the street view so you can zoom in just by double clicking or using your your mouse or if you're on a mobile app you could sort of use your fingers to zoom in and out the last thing i want to do before we move on to some custom styling of the map using a map id which is a really cool feature of google to control all of the styles of your map inside of the google console and just set an id on the map here for it to look the exact way you want we're going to set up this map and put it inside of a ref for us to access later when we're going to be controlling some zoom in and out automatically so i'm going to set up a ra a map ref here so we'll call it mapref and we'll call this use ref just like this and because i'm working with typescript what i want to do is give it a type a type hint here in these angley brackets and we can tell it that it's going to be an instance of google map just like that and i realized that i actually forgot to set up a few type hints here so what will the center be it's going to be a lat long literal and what will the options be they will be these map options here so this one and this one lat long literal is literally just an object a literal object that has the latitude and the longitude okay so how do we actually populate the value of this map ref well google map component gives us an onload function and so when it's finished loading it will call this function and it will give us the the ref to this map so what we can do is we can set up here and we're going to set up something called a callback basically a function that we don't want to run immediately as we define it but we don't want it to generate a new version of this callback function every time the component renders so what we're going to do is we're going to define onload here and we'll say use callback so it's very similar to use memo but it's specifically for when you want to optimize re-rendering with a function that's going to be called so what we're going to do is this function will receive an instance of the map and then what it's going to do is it's going to access the map map ref.current and assign it to the map and we will also pass in our dependency array right here so if i save this i can come down and say onload what you're going to do is call this onload function that we defined here via the onload callback and then we're good to go so we're up and running we've got the map rendering out we've loaded the script properly we've set up our api key next step is we're going to go style it using an id a map id so by default you get these colors on your on your map and they look great but what if you want dark mode and you want your map dark or if you want it um grayscale so there are ways to pass in styles to your map like a big json of options for styling there's actually an easier way and it's to define your styles inside of the google maps platform where we were setting up our api keys and our credentials and things like that so if you click down in map styles you'll see i already have two that i set up sort of like a dark i just called it leave for lack of a better name a dark version of a map a light version of a map here you can click create style they give you a few starting points to go off of dark mode and night a classic they also give you some industry optimized styles that show or hide different amounts of detail so if you're if you're doing logistics you don't need the same sort of what stores are side-by-side things like that you can also import if you've got your your map styling options elsewhere you can paste them in here and use that as a starting point what we're going to do is we're just going to maybe for this demo i'll show a night one and that gives us this map here and we can say open in style editor and this allows us to tweak everything so for example if we wanted to change the color of water we could come down here water geometry we could click this color and instead of uh black like it is here maybe we want our our water like this nice orange it's maybe not the most appealing to swim in but let's go with that so you can sort of make the map look exactly like you like you want changing transportation like roads and things like that changing what color parks are you could change sort of all of your geometry default colors here you get it exactly how you want it to look and then you save it and saving it for the first time publishes these changes so we could call this orange water save that now we've got sort of three map styles to work with once you've got that set up you can hop over to map management and this is where you create a map id and a map id if we click into this it's something we give a name to so we could call this uh react maps crash course we can pick what we're building this for so we're doing it on javascript and we can pick if we want a raster based map or a vector-based map let's go with vector and we'll save this and once we've created our our map id we can then choose which style we want to go with so i'm going to pick the one i created earlier called darkly that shows what our map will look like we can save it and what this gives us is a map id so we can come and copy that map id go back into our code and specifically where we set up our map options what we'll do is we'll just add a new one so we'll say map id is equal to this string and this one i am just going to hard code here it's not something secretive so we can just leave it in our code sort of exposed that's fine so we're going to save that and if we go back then and look at what our map is rendering like okay so the the colors have shown up i just waited about 30 seconds or something like that so now i have this nice dark mode map where i've customized the the color of the water here and we have a nice dark mode theme to work with so that's how you can customize the look and feel of your map by setting up styles and creating a map id inside of the google maps platform the next thing we're going to work on is getting the places search showing up here so that we can find where our office is and put that office as a marker on the map we're going to be adding a google places search box over here on the left right under the commute h1 tag and that will allow the user to search for their office and place that as a marker on the map so i've already imported a places component that's sort of an empty placeholder that will fill out right now but we're going to use that component right here in controls we'll do places like this and you can see that it's got a typescript error because it's expecting to receive a function called set office so we need to pass in set office and what this is going to do is basically update some state so state to basically store the latitude and longitude of the office that they selected so why don't we go set up that state first so we'll say const office and set office is equal to use state just like that and we'll give it a type hint of what it should expect to receive and that will be a latitude longitude literal just like we've used before so if we come down what we're going to be doing is passing in um a function just like that and what it's going to receive is a position or a location so we'll say position and then this position is going to call this set office function so set office given a position and so why didn't i just pass in this exact set office function here because i don't just want to update state what i want to also do is move the map to that location so we can do that by accessing our mapref just like that and because this mapref it may be missing because at the beginning it's not initialized so if you just do dot current um and then pan two which is the function you can see that it starts to add some question marks here because it might not be available so that's good it added in automatically and where we want to pan to is this position so if i just save this basically we're calling the places component okay it's not really showing up yet just this word places showed up so we have to go into places and implement this actual code so rather than just returning a div we need to show a combo box which allows a user to search through google places you can see that i already set up the type here of this set office function that's going to receive a position a latitude longitude literal good so we're good to go we've already passed in that function now it's time to use it so the package i like working with for using google places is this use places autocomplete which gives you a hook use places autocomplete and it returns you a whole bunch of values that you can then use to con to display and control uh how google places works there are other react packages that that do more of this for you but it sort of takes away some of the flexibility you have with this package so what we're going to do is we'll extract some values out from this object but we're going to start by just calling use places autocomplete and what we need to pass in nothing we're good to go and we don't have to set up loading the script or anything like that because remember we already did that here at the beginning when we were just starting out with the maps and we told it we want to use the places library which is key because that's required to work with places autocomplete so what this is going to give us back is a boolean called ready is the script ready to be used in our case it always should be because we've checked this is loaded here but it's good to keep this check just in place so we're going to get the value that the users entered into an input box we're going to also get a function set value to to change this every time they they type a letter we're going to get the suggestions themselves but this is actually broken out into two things uh the status of whether we actually received some suggestions okay or not and the actual data of those suggestions themselves finally one other function we're going to extract from this object is something called clear suggestions sort of whenever they've selected one we can remove the list from the screen of the suggestions we're showing to our user so if we save this a lot of values that we're extracting but we're going to use them right now so what i'm working with for my actual combo box is this package called reach combo box and what we start out with on the outside is this combo box itself so we'll do combo box and to that we're going to have to pass an on select function let's not fill it in yet we'll come back to this in a second but inside of the combo box what we have to do is the input itself where the user types into so we'll use the combobox input just like that let's convert it into a component and we need to pass it a few different props so the first prop we have to pass is the value that the user has typed in next is anytime they they change that value we have to listen for that event so on change that gives us an event and then with this event what we can do is call set value which would be the e dot target target being the input itself dot the value that they've typed into this so by default we're going to disable this if it's not ready to be used and i'm just going to give it a class name that i've set up um called combo box input combo in a box combo box input um what's inside of this is just setting some width and padding of this so that it takes up the space of the container that it's in so i'm going to hit save let's come back and view here we have it showing up the user may not know what they're expected to type in here so why don't we come back here and we'll put a placeholder so the placeholder we're just going to say search and address or search you could say office address to be a little bit more clear right here so if we were to type searching so if we search for like the google kitchener office which is somewhere up in here we may be getting suggestions back but we haven't shown them yet anywhere on the screen if we were to come in and just do console.log status and data and then pop open this console here and you can see here we're actually getting some results back and the status is okay so it's actually working correctly but we just need to display them to the user so if we come back here right below we're going to put the combo box popover just like that and inside of the combobox pop over we have the list of suggestions so combo box list just like that and inside of the combobox list first what we're going to do is we're going to check if the status is okay so it's just capital letters okay that's google telling you that you've been able to load the places correctly and you've got some suggestions to work with so if that's true what we're going to do is we're going to map over the results so data.map and what it gives us are basically two things we want to extract the first is the place id we can use that as a key for all of the options we're going to show in this list and the second thing we want is the description of the place itself so this is going to render out a combo box option just like that and we're going to do this so it's giving us an error and it's saying that you need to have what are we missing here an option that is suggested no overload matches so we're missing a value we're also missing a key because we're iterating over this so we'll pass in pass in the key of the place id and we'll give it the value of the description and hopefully if we do that typescript will correct itself and we can come check if it's displaying things correctly cool and it is even sort of it still had that data in state so now it's rendering correctly here's where that google office is i wanted to show on the map but remember we haven't finished this on select function yet so what we're actually going to do is we're going to come up here and we're going to say const handle select and this is going to be the function that we call when they selected so it needs to be asynchronous because we're going to be working with promises inside of it and this function is going to receive a value that's a string so whatever basically it would be this whole string here google breithaupt street kitchener ontario canada so inside of this what do we first want to do let's first just update the value to be what the user has selected so this receives two things the string itself val and should fetch data we're gonna say false because we're we're we're not asking it to go and load more data we've chosen a selection so once that's done we can clear out the suggestions because i think once you select it we shouldn't keep showing the list of suggestions to our user and after that what we need to do is call a couple of functions imported from use places autocomplete to convert from this address string into coordinates so the first one we're going to do is going to give us some results and we are going to await a get geocode so geocode takes in [Music] an object that has an address of this val here so basically whatever text is showing up here and what that will give us back are a bunch of results that can then be we can extract the latitude and longitude from those results so what we're going to do now is we're going to say const lat and lng is a weight and we'll call a function called get lat long and what we need to do here is pass in a single result so the single result will be results zero so whatever the first result is we'll pass that in so once we have that we have the latitude and longitude of whatever place they've selected so we can then call our set office function so set office it wants to receive a lat long literal so we'll pass in lat lng just like that cool so typescript is corrected we need to pass the handle select down to on select here and then if we were to choose this you can see it panned to that location so it's working correctly because when we called set office that was the prop the function passed in and what this did was it set that position into state into this office state but it also panned the map to that position so we saw it pan the map which was the reason why we had the reference but why don't we actually just show the marker on the map right now so what we're going to do is inside of this google map we will say if there is an office so and and we will show the marker so i've imported already a marker component marker just like this and so on its own it gives you an error what it's expecting to receive is basically hey where do you want to show this marker on the screen so for that we'll give it a position just like that and we can pass in our office because our office is a latitude longitude literal which is what the position expects to receive just like that so if i were to save this come back here scroll up we are now viewing kitchener with a marker on the map so things are working as expected now one thing i wanted to do is i just wanted to update um the marker from showing the default red one to a little like less differentiated a bit because i'm going to be showing other markers later and i want to differentiate my office from the different houses that i could potentially buy and then commute to this location so what i can do here is i can just go to the marker and i can say icon and you can pass in any url and i've loaded one already that's a beach flag so if i were to come back here we have the beach flag showing up just like that awesome so at this point what we want to do is we want to start to show some concentric circles around where the office is to sort of start to indicate where are the commutable distances so the whole point of this map is to basically see well if i work here where can i buy a house and have it be some sort of sane commutable distance to get to work because if i'm going to work the average american works 260 days a year twice a day you're commuting there and back the further away you are from your office uh the harder it is to get to and the more gas you have to spend and the longer you spend time in your car so we're going to draw some circles around here that sort of show like commutable semi-commutable ah it's pretty far away and we'll start with about 15 kilometers distance and then 30 and then 45 kilometers so for that what we're going to do is basically inside of this like i guess it's sort of like an if statement here like if an office then render this out you could do this with a ternary as well but i like this sort of shortcut approach what we're going to do is we're going to start by putting this fragment around it so that we can place additional things inside and we're going to be working with a component called a circle so circle is something i had already imported up here at the top and to a circle what you do is first you tell it where to position itself you don't use position though you use center so i'm going to use the same office location as the center and we need to tell it the radius as well so radius and you do this in meters so 15 if i want kilometers a kilometer kilometers a thousand meters so we add three zeros to that so if we were to come back here you can see this dark circle it's drawn around this location you can then go and apply some different colors and styles to it which is all of this setup that i had done below basically i'm setting the stroke opacity how how thick it is what the colors should be so for the close one i've got close options middle options and far options so what we're going to do is we're going to say options and we're going to pass close options so now i have a green this is like yes you can commute from here next one if i just copy this we change it to 30 kilometers and we use the middle options that's like you could maybe commute from there but you're starting to get pretty far away from your office and then the next one will be the 45 and that's starting to get pretty far away so we'll use the far options which draws that bigger red circle around it so if we zoom out on the map sort of like the further away you get from the office the more difficult it will be to commute there that's that now what we want to do is start to show the houses on the map so we can basically choose one and it will show us how do you get from that house to your office and how far away is it so remember i talked at the beginning for a second i've got this function called generate houses given a position let's say where the office is for example or where the center of the map is maybe that's another approach just generate a hundred houses sort of randomizing their latitude and longitude so it sort of displays on the map you'll see it in a second we're going to call this function generate houses up here at the top we'll we'll just do it below here so we'll say houses is equal to use memo and use memo will be a function and for this we will have a dependency we'll say this center value is our dependency so that inside of here what we can do is we can say generate houses for this center location so anytime the center location changes that will regenerate houses and place those houses inside of this array here and with this set up we can come down to our map again and maybe below the office location we will just render out the houses so we'll map them out for each house what we want to do is display a marker and that marker will have a position so that would be the house position and we need to give it a key because we're iterating so for key what you could possibly use is just house dot maybe it's latitude hopefully we don't have two houses with the exact same latitude if you were really worried you could combine latitude and longitude together to make it a little bit more random and i think that's all we need to get these houses showing up on the map maybe i have an error actually no it doesn't look like it let me just re-reload the screen let me choose an office so kitchener google actually no google kitchener sorry perfect so when i choose my location on the map that triggers it to go and find the houses and then i'm showing those houses on the screen and you can see they're sort of randomized out we've a few in the green area and you've got some further and further away so with a hundred houses it's it's doable but you're starting to get like it's i think it's calling for clustering basically in this region there's there's four in this region there's two etc so we're going to come and we're going to use the marker cluster component from google to basically cluster these locations together so popping over to the code clustering is extremely easy to get set up what we're going to do is use a component called the marker cluster and as a child to this a component you have to pass a function that when called will receive an instance of the cluster itself and as a return value of this arrow function we want to basically return all of the houses to render out so we'll just cut and paste that inside of this function we'll clean up this these brackets here and the only other thing we need to do is pass this instance of the cluster to the marker itself so there's a clusterer prop and then we pass the clusterer instance and if we come back we have our houses being clustered together in groups so google uh the the controls and clustering that they have set up will automatically um put them in the right groups at the right zoom level and as you click into one it will sort of reveal the next zoom level down so sometimes it will then show individual houses sometimes it will just show up smaller groups of clusters that you could then click into and eventually you'll get down to the actual houses themselves so that's in what one minute we were able to add marker clustering to our map next we want to add the ability to click on one of the houses so if i zoom in in the clustering and click one of these markers i want it to draw directions from whatever marker i clicked on to my office and that will then show us or give us the information to know how far will it take to commute to this office so what we're going to do is add an on click event handler here which we'll call an arrow function and this arrow function is going to call something called fetch directions we haven't created that yet that's what we're going to do right now and to this function we're going to pass the house which if you remember is just the latitude and longitude literal so let's go to find this fetch directions function so we'll come up here and we'll say const fetch directions and that is equal to it's going to receive a position which is a lat long literal and then in the body here is where we're going to do the work to actually call the direction service to to be able to calculate the directions from basically the position to the office so what we're going to do is first of all we're going to say if there's no office we are going to just return because in order to get directions we need both the office and the position of the house so why don't we actually call this explicitly house so with that done what we can do is create an instance of the direction service from from google so we'll say the service is equal to a new instance of google dot maps dot directions service and then we can use this service to basically find us the directions between two routes so we call service dot root and then what it wants to receive are basically what is the origin so we'll say it's from the house and what is the destination we'll say it's to the office so we're going from the house we're thinking of buying to the office and how are we going to get there what is the travel mode because it could be car bike walking we'll say that the travel mode is dot maps dot travel mode dot driving that's how we're going to get there so what we do is we pass in another function here that's going to receive the result and the status just like that so inside of here we're going to put a quick if statement that says if the status is triple equals to okay and there's some results for these directions then what we can do is basically take these results oops result and let's put them into some state so we don't have any state set up yet to store the directions so why don't we come up here to the top and we'll say const directions set directions is going to be use state like that and for a type hint we'll pass in the directions result like that so now we can come back here and we can say set directions and we'll pass in [Music] the result like that so just to go over this again we create a new instance of the direction service and then we route it from the house that the user clicked on to the office via driving and then the result we place inside of state and once we have that inside of state it's now time to show these directions on the map so what we can do is we can come back down inside of the map and we can check if there's directions then render out the directions renderer which is another component that we're bringing in from the react google maps api package so it knows how to receive these directions results and render them out so what we do is we pass in the directions here as directions and then we can pass some options so if we just save it like this it should work let me search for google kitchener again [Music] and then we'll just choose one of the houses and it renders out directions it's actually looking pretty good we don't really need to change anything but if we wanted to we could come in and we could pass some options like this and the types of options you might pass in are like how to draw the line that's rendering out sort of the directions on the road so we could say that we want to have a z index of 50 so that it comes above any of the circles that we've rendered out on the screen already and then we can give a stroke color of uh there's this color 197 60 is this nice blue and then we'll give it how thick the line should be so a stroke weight of five so if i just save that come back i think i have to get the directions again so let's go to this one this time and now you can see it looks similar but because of the z index it popped it on top of the concentric circles that i'm rendering out so that's how you can get the directions and then use the directions renderer to to draw the route from your origin to your destination so next what we want to do is basically just display some information about the directions to from the uh from the house to the office and particularly like how long it will take to get there and what if you did this 260 times a year twice a day how much time would you be spending in your car how much money would you be spending on gas so we're working inside of these controls this div over here on the left and right below where we put the places i'm actually going to start off taking a step back what if the user arrives here for the first time what are they supposed to do so we're going to give them some directions where we just say if there's not an office then render out a p that says enter the address of your office just like that cool so now they know what to do so we'll put in google kitchener as the address that will show all of the houses on the map and we'll choose one of them so that it renders out the directions to get from there to the office so now we want to show information about the distance of that route so right below here we're going to be working with a distance component that i've imported so we'll touch on all of this in a second for now we're just going to call it we're going to say if there are directions then show the distance component and it wants to receive one leg of the journey basically so if we look at the directions in general there's often multiple routes you could take to get from the origin to the destination so we want to first access let's just say the first route so whatever the default one is and then specifically uh the first leg of that route so we'll say legs zero just like that so now we come over here to distance and we could just render out console.log of the leg to see what sort of information it gives to us so if i go into the console here's the leg and we get a bunch of information like the start location the end location we get distance and duration so where i chose on the map the duration is 33 minutes which is this many seconds and the distance is 41.8 kilometers which is this many meters so we're going to be working with this text and value here to basically calculate some things about how long you'll spend in a car each year so for these calculations i've set up some constants how many times does someone typically commute per year according to google it's 260 times times two so there and back and i put in some calculations about basically the fuel efficiency of a car so in canada we often use the number of liters to drive 100 kilometers as like a standard fuel efficiency calculation so i said here you use 10 liters of gas to drive 100 kilometers but if i want to know how many liters to drive one kilometer i can just divide it by a hundred how much does gas cost it's about a dollar fifty per liter right now so if we multiply these two together that tells us basically how much it's going to cost to drive one kilometer that's important because then we can use these calculations here to figure out how much it's going to cost us so seconds per day this is just there's 60 seconds in a minute um 60 minutes in an hour 24 hours in a day so this tells us how many seconds per day because remember google is telling us this in seconds so that's why i needed this constant setup so the first thing we're going to do is we're going to just put an if statement here mostly for the purposes of typescript otherwise it's going to give us an error because there's some optional values so we'll say if there's not a distance on this leg or if there's not a duration duration we're going to just return no so if you don't have those just don't bother rendering anything next what we're going to do is figure out how many days a year would we be driving if we commuted 260 times times 2 there and back from the from the home we chose to the office so for this we'll say days is equal to math.floor to just round down to the nearest day basically so we start off with how many commutes per year are there times the leg.duration divided by because it gives us in seconds we divide by seconds per day so if we save this and we just render out the days here what it's telling us is if we wanted to buy this house commute to this office and we did it every day twice a twice a day for 260 times a year we'd spend 11 days inside of a car it's quite a bit of time to spend inside of a car and we can actually then calculate what would the cost be if we were to do that so we'll say cost is equal to let's also do math.floor to just round down to the nearest integer so what we'll do is we'll say the leg distance value divided by a thousand because they give it to us in meters we want to convert to kilometers and then we multiply by liter cost kilometer and then we multiply that by how many times you commute per year so commutes per year this now gives us i gave it a cost this gives us a cost so it would cost 3 256 if you were to do this commute um every day for a year or 260 times per year so given these values we can now display sort of a nice message to our user about what is the true cost of basically this commute so we'll put it inside of a p tag and we'll say this home is and i'm going to put this in a span to highlight it so class name of highlight so we can say leg.distance.txt away from your office so let's start with that let's see how it's looking so this home is 41.8 kilometers away from your office perfect and we can say that would take and we can do another span so span with a class name of highlight so now we can use our calculation so we can say um so after that if that's the distance how long would it take each way we can say that would take and then we'll put another span here with a class name of highlight and then we'll say leg dot duration dot text each direction so if we save that we now say this home is 41.8 kilometers away from your office that would take 33 minutes each direction so that's what each commute would take but what if you were to do that 260 days times two commutes per year well now you get to use these calculations that we came up with so we'll put another p and i'm gonna just copy this so i don't have to keep pasting it so what we're gonna say is that's here and we can say days days in your car each year at a cost of and we'll paste this highlight again so cost just like that so we come back and we see that's 11 days in your in your car each year at a cost of 3256. so maybe we want to format this as dollars what we can do is we can just put the dollar sign here and then we can come and if we want to get commas showing up correctly we can say new intl dot number format dot format the cost so this is some in internal number formatting built into javascript in the browser so we're going to format the cost for whatever location your user is located in so it puts commas in the right place basically so that's 11 days in your car each year at a cost of 3256 dollars so now you know sort of the true cost of if you were to buy a house and commute so if you go into the green zone it redoes the directions and now that's down to seven days and only uh twelve hundred dollars and if we go really far out like let's say we're going to go further out of the red zone way over here now that's 21 days you're going to spend in your car each year and over 6 000 if you were to live here and work here so now you can figure out the true cost of that commute on a yearly basis that's all i wanted to show in this video and we we covered an awful lot if we were to sort of review what we did we started off just by rendering a map we applied some custom some customization via styles and the map id to our map we then worked on searching for our office so we'll do google kitchener and when we choose an office we we rendered out some circles of sort of 15 kilometers 30 kilometers 45 kilometers away sort of good commute average commute pretty bad commute we rendered out the markers then we cluster clustered them and we added an on click event that would calculate the directions between the location you chose and your office then we used that directions object to render out some calculations of how much that would cost you if you were to do this on a yearly basis hope you enjoyed the video and how powerful working with google maps in react can be take care bye
Info
Channel: Leigh Halliday
Views: 98,333
Rating: undefined out of 5
Keywords: How to build a map with React and Google Maps Platform, build interactive maps with Google Maps and React, How to use Google Maps in React, Apply custom styles using a Map ID, how to Add search with Google Places, How to Render Markers in Google Maps in React, How to Cluster Markers with Google Maps in React, How to display directions with Google Maps in React, Google Maps Platform React crash course, react
Id: 2po9_CIRW7I
Channel Id: undefined
Length: 57min 21sec (3441 seconds)
Published: Mon Feb 28 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.