Google Maps API v3.36 Tutorial - February 2019

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys just before I start this video I just wanted to say thanks to everybody that subscribed to my channel I made a like five part full-stack react out tutorial I just wanted to say thanks for everybody that enjoyed it like I got a lot of positive feedback on it I thought that was really cool like when I wanted to learn how to like use react to make an app I found I had to research like a bunch of small little things to really figure out what was going on to be able to wrap it all up in a bow it was kind of what I was going for and I think I kind of achieved that you know I kind of just did it for fun but the positive feedback I got I thought was really cool so you know I thought I'd try it again so you know let me know what you think and I hope you enjoy the video hey guys my name is Bryce and today I have a pretty fun tutorial planned we're going to be looking at how to use the latest version of the Google Maps API and this is in February 20 19 so that's Version three point three six and looking at some interesting ways that it can be used so you know at this point we're pretty used to seeing Google Maps you know or any map in general like on different web pages like on like a you know that contact page or store locator page of a business's website so you can do interesting things like that but I also just wanted to show maybe some more inspiring interesting ways that map could be used in a website in general so let's just get into it I also just wanted to mention that I'm gonna have timestamps in the description below so if you ever want to skip a certain section just feel free to look down and click one of those links so I'm just here on the overview page for the Google Maps JavaScript API and I just wanted to start by mentioning you know I started playing with this a couple years ago and there's been some recent changes so to how you get started with the API so I just wanted to talk about that a little bit so as with most API is you need to get an API key before you can start using it so in the past you were able to get one of these with your Google Account and just jump just get started but Google has recently changed its policy and now you have to enable billing on your account before getting a key I'm just gonna show you how to get started if you don't already have a key so if we scroll down and go to the link where okay are you using a not a API key so you know maybe you created one before if you did then that's great but I'm just going to show this as if we haven't started so no I don't have one and they can take into the page to get an API key so I just wanted to point out also these links at the top different things that you can do to best protect your API key and just best practices associated with that I'm not really going to go through that today just because we're only gonna be developing on our localhost but there's things there like you know you want to restrict for example API access to a certain URL if you're developing a map on a particular webpage so you can restrict it to have requests only come from that domain which you have hosted your map so again I just wanted to cover mainly this concept of billing it can freak people out a little bit just because you kind of have to provide your credit card now and you don't want to run up like a massive bill so I just wanted to clarify a few of those concepts you can see this big reminder in red about enabling billing before we can get started with the JavaScript API so if I just click this link it's a bit of a dense article but I'll just kind of summarize it quickly because I think it's important to be kind of you know upfront about this and if you are gonna be providing your credit card I don't want anybody to be overcharged so you know they summarized it here this has changed over sometime last year in about July so they they kind of summarized just saying it's it's a pay-as-you-go model as you know that's the standard with most cloud services and the cost is calculated by you know the way the api's are combined into this thing called a skew and you know an API may have more than one so for example in the Maps like there's like it's kind of divided up into like a places API versus just like the map API itself and the cost is calculated by the price multiplied by how much you use that SKU but the good news is that every month you get a two hundred dollar credit in US dollars which if you're a Canadian it might be a bit more than that with conversion rate and yes so we get that credit every month so if you keep your use within that limit then you don't have to be you don't have to worry about being charged even though your credit card is connected to your billing account but even still you you know you want to be careful just about like who who's using this you know today we're just gonna be developing on our local machine so it's not like anybody's going to a website and just executing at Lino making map requests like at an unstoppable rate we know because it's on our local machine it's within our control so you know we don't have to worry about that so again just just very you be careful about you know where you're gonna be developing your map who is going to be paying for this and just the usage that that map is going to be receiving and I just wanted to take us back to the API key page and look at the fa Q's because I just want to make this abundantly clear here we go how much does it cost to use the Google Maps platform so again so if you are below that complimentary 200 dollars per month usage your usage is free just as it was so I'll drop a link to this FAQ page and I will also include there's a calculator that Google provided to basically estimate what your usage and billing will be like based on the tier that you picked and you know of what kind of traffic your site may be having so I'll drop a link in that in the description below and you can check that out as well just to figure out what's best for you so if we go back we want to go back to the get API key page and we're gonna go down and just click this fancy little get started button so here we are so we have this dialogue pop-up and we want to pick which products we want to include we've got three here the routes is for you know doing kind of the directions and distance and things like that but today we're just gonna pick the maps and also places and then we'll click continue so we're gonna create a new project and we'll name that I don't know my map or whatever name that you would like I'm going to click Next so it's redirecting us to enabling the billing so I already have a billing account set up because I've done this before but if you don't then you're going to want to follow the steps where you'll provide your credit card in that type of information that we mentioned before and then you'll be able to enable your Maps API so I'm just gonna click set account since I've already done this and there we are we're ready to start developing and we have our API key here so again just follow those steps and you will eventually get your API key as well so I'm gonna copy that and paste it somewhere for later I also just wanted to point out within the cloud platform portal here that this is where you can actually restrict where the API can be accessed as I as I mentioned before so that specific websites web servers and even apps can be the only ones that can use your API key just in the case that you know somebody else grabs ahold of it and you know if they made use of it it would be charged to your billing account and you wouldn't you wouldn't be too happy with that so again the secure credentials if you go here you can set that up all right so enough of me rambling about billing we're ready to get started so if I switch over to my text editor I'm just using vs code but whatever editor you want to use is fine too so I've set up just some basic basic set of files to get us started we've got our main index.html page we got a style sheet it's blank right now and also a just main JavaScript script and I'm also using the live server extension 4 vs code and that all that does is just live reload the page in our browser whenever we make a change so we don't have to manually refresh like a hundred times so I'll start that up and we can see our page pop up there I'll just expand that so we can see what's going on on both sides I made the font huge and v/s code one of my last videos that was showing up pretty small so hopefully everybody can see this okay so nothing crazy going on here we just have our standard kind of HTML document and I just included bootstrap for the hell of it just for the responsive features and just to show how you might include other scripts here alongside the Google Maps API script down here and I just have our stylesheet and script attached obviously and just some code here basically to get us started so the first thing we're gonna want to want to do is create a container for our map so if we go down here we do div and we want to give it an ID of map then we want to jump over to our stylesheet and just add a rule for that we want to give that map container a height so we're gonna give it a height of 500 pixels easy enough save that and now we need to provide our API key to the script tag that I set up down here and that just starts as question mark key is equal to this so I'll copy and paste my key so lastly we just need to add another argument to our request URL and it's just the it's going to be the name of the function that we want to be called when the script has been loaded so we're just going to go here and add callback is equal to create map and then an ampersand and then we'll switch over to our script file and okay we'll start by creating a variable called map and then the function create map and in there we want to first start by making a variable called options it'll be a object the first attribute will be Center which represents as you probably guessed the center of our map so I'm just going to copy and paste that it's an object that just contains two attributes for the coordinates which is latitude and longitude and then we'll also just add another attribute called zoom and obvious again it's just how close we are to the ground in the map so finally to get our map to render we just have to call the map constructor passing in our container that we created earlier just the div so if we go map is equal to new Google Maps done map we pass in the reference to that element so document get element by ID in the ID was map and then we also pass in this options object to configure our map so if we save that in our page reloads there we go we see our map appears you've embedded a Google map into a web page for the first time Congrats taking big steps today but let's just see what kind of options we can use to customize our map so I'll put a link in the description to just the documentation unlike the hole reference of different map options but I'll just show you a couple that I have written down here off the top of my head so if we go and we set an attribute of disable default you I set that to true we save it'll reload we can see that all of our standard controls are now gone so this might be you know choice if you don't want your user kind of leaving the location you've set up in the past we can get rid of that now we'll try another one there's another one called draggable and set it to false and this is kind of an obvious one too whereas before we would have been able to drag our map and move it around we can't so again maybe it might be a choice for you know keeping your user in the same sort of spot here's another interesting one go and change if we go to the map type ID this is going to set the view of the map that we see so whether we want it to be a road map like it is right now or if we actually want to see like some satellite images or maybe a mix of both we can set the map type ID to be something different so if we set it to hybrid for example and it also works if you can pass in a string but this is also just like the reference to the actual like the innumerable string option kind of thing so if we save this we can see that it reloads and we have the hybrid view so it's the combination of satellite image with the roads pretty cool so let's get rid of that and we'll set it back just to our default map again so now let's say we want to do something different like we want to customize this style as in like the colors and just the appearance of the map there's a whole host of different style settings and I'll put a link to that in the description again I'm not going to go through and explain all of them but there's a whole convention that needs to be followed but I'll just copy and paste some in that I found kind of cool-looking let's put that in there you can see there's a whole bunch of different JSON objects so they kind of just pick different element types and you can do change the appearance of them like by providing a color or you know like different opacity different things like that and there we go so when we've saved and reloaded it's you know we have a really kind of interesting funky looking map there so you can really you have a lot of control and again I'll put the link to all those different settings so once again I'll just reset it back back to our boring default gray map and now let's take a look at instead of looking at the controls and styling we'll look at adding some functionality so maybe it's something you've already wondered about but what if we wanted to make our map default to the users current location so we can do that using the geolocation API that's available in most modern browsers so if the user has location enabled on their device we can use that information to Center our maps let's set this up I'm going to start adding a variable at the top called info window and then we'll initialize that with info window with the constructor provided in that google object and by the way like in case this wasn't clear we have access to these the google object and these references because we included the Google Maps API script it drops those things in there for us so the first thing we're going to do is we're going to check if navigator dot geo location so this is checking just within the browser if geolocation is available so if it is available we can use this method to get the user's current position otherwise we want to just display an error message so if we go down here create a new function called handle location error and we'll take two different arguments content and position and in there we'll use our info window calling the set position method passing in our position and then also using the set content method which obviously sets the text of the info window and then opening the info window on our map so calling open and passing in our map reference great so we'll call that from our else block if it is the case that the user doesn't have geolocation available in their block browser so just call handle location error and we'll pass in the message no geolocation available and then passing the position of just remaining at the center of the map but if the user does have access to the geolocation API we'll want to call the get current position method of that navigator so we'll go in here the navigator dot geo location get current position and that takes a callback function to run when the position arrives and they'll Pat be passed into this parameter P and there's also a second callback in case there's an error so if there is an error we want to once again use our handle location error function that we created and we'll put in a message of geolocation service failed and once again defaulting back to the center of the map but if we do have a position and everything worked out fine we'll start by making a variable called position and it'll have two attributes lat and lying but we'll fill in these attributes passing in the chords attribute of that the position that gets passed back from the browser and then the latitude of that and also the same thing for the longitude and the reason that we have to do it this way is just because we need to get our object into the format of a coordinate that Google Maps expects so we have that and then finally we're going to set the position of our info window to be this position that we just created and also set the content so setting the text of our info window to be your location and then finally opening the info window on our map so if we save this and our page reloads we're gonna see now that there we go it's if you're in Chrome or another browser probably a little message will pop up and say it will ask you for your if you have permission to provide your location and there we go they provided mine very cool so alternatively we could have also went one step further and used our map object to set the center to be that position but instead it just biased the viewport of Google Maps to contain the info window in the position that we just put it in so I'm just going to reset this back to our default map so moving on let's say we want to be able to search an address or a place and direct our map to that location so this is why we enabled that places API earlier when we were getting our API key and with that being said let's switch back over to our main index dot HTML file and we're going to add the libraries sorry we're gonna add the places library to our URL so using the parameter libraries and it equals oops places so we'll save that oh and also in our index dot HTML we're going to add a new row just above our map and within that column we're going to put a text input and we can see our search bar popped up above our map and if we switch to our main script file we're going to initialize that input by well first we got to grab the reference to it so get element by ID search and then we're gonna initialize the search box so this is again a Google Maps constructor passing in that input document I'm sorry that input element so the next thing we want to do is make it so that the search results are biased towards the locations that are already in the maps current viewport in this case in Toronto and kind of the surrounding GTA so because unless the user is looking someplace entirely somewhere else they're probably hoping to find a location in the vicinity of where the map already is so we just want to first load those locations that are in the immediate vicinity so we do that by adding a listener for the bounds changed event on the map so go map add listener balance change passing in a callback function so within this callback we want to set the bounds on the search box to the bounds of the map so the search box set bounds to our Maps bound great so now we want to see the search results on our map so let's make an array called markers and now we need to add a another listener for the places changed event on our search box so search box add listener place has changed and passing into callback function so this callback here will fire when the user selects a prediction from the list so let's start by storing our places so we'll go variable called places and we'll get that from calling get places on our search box then if we find that no other places were found meaning that the array is empty then we don't want to do any other work with our places so places dot length is equal to zero then we just want to return otherwise we'll continue on so the other thing we'll want to do is clear out any markers that were placed before and this won't be necessary the first time that we search but for every time afterwards so we'll call the for each method on the array which takes a callback function passing in that the you know current marker within that iteration and on that marker we're gonna call set map null just getting rid of the map the reference within that marker and then we're also gonna reset our markers array back to an empty array now we're going to create a bounds object which is the coordinate boundaries of a map so we'll make a variable called bounds and we'll set that to new Google Maps that Lang bounced and now we're gonna iterate over the array of places and add a marker for each and also adjust the bounds of our map so we go two places for each we'll check if the place has a geometry attribute meaning it has data to get to be given a position on the map and if it doesn't so if not P geometry then we're just going to return because we don't want to do anything with that place then next we'll push a marker to the marker array that we've created before otherwise if it does have a geometry associated with it so pushing a new Google map stop marker which accepts an array of options and the constructor object will take a few attributes so the it will take the map it'll take a title which will give it from our p object here we'll give it the title sorry the name attribute of that place and then we also pass in a position so we'll grab that from the geometry object and then the location attribute finally we want to update the bounds of our map to take each place into account so if the geometry of a place has a viewport attribute so if P geometry has a viewport then we want to pass this in to the Union on our bounds object that we created before so meaning that if this place is a preferred viewport we want to set the bounds to a combination of what they are with this new viewport included that might be a little tricky to understand I'll include a link to the documentation for that if you want to learn more and otherwise if it doesn't have a viewport and we want to pass in the location to the extend method of our bounds P geometry location and finally we want to call the fit bounds method on our map object and pass in those bounds to put them into effect so if we save this and our page reloads we can try searching for a place so if I try Art Gallery of Ontario which is in Toronto you can see that our map updated and it marked that place for us that's great so we added a search box and we can update the map based on our searches so I'll just reset back to our default map once again so moving on let's say we wanted to use our map for a slightly different purpose like showing information at different locations we can actually visualize geo JSON data on our map and customize location markers to display this kind of information so let's try that out with earthquake data from the US Geological Survey so to start let's zoom out of our map and make the center somewhere in the Pacific Ocean so if we set the latitude to zero and the longitude to 130 and set the zoom two to be zoomed way out and I'm also change the map type ID to be terrain now we're gonna get our geo JSON data so this could usually be done in a variety of ways like via an API or maybe just an async request to a back-end but this time we're just going to attach a JavaScript file that already has can already contain some geo jason embedded within it and if you don't know what I'm talking about when I say geo JSON if I just show this website here to the side it's basically just a specification for encoding Geographic data and we can see a basic example here so there are a variety of object types that you could expect but they all follow this structure roughly where you have like a type attribute a geometry object and then a properties object and this properties object is the one that we're interested in since it will contain our data but more on that soon so we'll create a script element to attach the GS file that contains our earthquake data so we do this by creating a variable called script calling documents create element script and then we're gonna set the source attribute of this script to be this URL and I just paste it in I'll put that in the description below so you can grab that or otherwise you could grab it from the source code on github and then just underneath that we're going to actually attach the script to the head element of our HTML document so get we do that by getting elements by tag name head and then for the very first one the only one we append the child our script as a child all right now we're going to create a function that returns a JSON object containing the styles for the data point that will be displayed on our map so we'll call this function get earthquake circle and we'll pass in the data value as a parameter and this this function will just return a JSON object with all kinds of different style properties and I'll just paste those in now the most notable one here just being well so the type of symbol that we're using so we're just using a circle and the scale is a formula just applied to our data value next we need to add the Geo JSON to our map so we'll implement a function that is called in the script that we attached and passes in the data so this function is called EQ feed underscore callback and it'll accept geo jason as a parameter and then within this we'll just call on our map object and the data attribute the add geo json method passing in that geo jason parameter great and lastly we need to set the style for our data points so back in o you can see it's already starting to pop up if we go back to our main function we call map the data attribute and set style we passed in a callback that accepts the feature parameter and as I mentioned earlier we need to get the earthquake magnitude data from the properties attribute of our geo JSON so if we want to grab this on our feature we'll store it in a variable called magnitude on our feature we call the get property meth and the property name is Meg that's the actual within the JSON data that's the one that holds the value and then we're going to return a JSON object which specifies the icon attribute and we'll call our get earthquake circle function and passing in the magnitude so if we save this and our map reloads can see our data pops up awesome so data visualization is becoming quite popular these days obviously and there are tons of scenarios on the web where you could display Geographic data in a meaningful way like this so that's pretty cool so once again I'll just reset our map all right so we obviously have a lot of features at our disposal styling our map finding places even visualizing data but this last demo I just wanted to show you is even more fun we can actually draw editable and draggable shapes on our maps using coordinates so I'll start just by setting some basic settings for us again and going to let's see 4 3 6 4 2 as the latitude and negative seventy nine point three eight nine as our longitude and we'll set the zoom to 16 and we'll set the map type to satellite so our page reloads we can see we find ourselves in the heart of downtown Toronto and suppose we want to wrap a polygon around the Scotiabank Arena here and inspect the coordinates that make up that space so first we're going we needed to find an array of coordinates for that polygon but before we do that we're gonna have to move our latitude and longitude values into variables so if we create two variables a and B we'll just store the values in those variables and replace them in there then we can actually oh and we're going to need to include another one called diff which is just going to be creating an offset from our coordinate values so we'll set this to zero point zero zero three three and then below our options we can define our array of coordinates so these coordinates just basically create a box around our center of our map that our location that we provided so now we can go and we can create our polygons so they'll call the polygon constructor and that'll accept an object with various attributes so I'll just paste that in kind of go through them so again we pass in our map as a reference the paths is our polygon coordinates that we just defined I have some colors to find here the opacity and then also adding the draggable and editable attributes so if we save this and our page reloads we can see that a polygon appeared and we can move it around and we can adjust it very cool now let's say we want to display or even perhaps store the coordinate data for the polygon we can do this by attaching events to the polygon paths so first we're going to create a function called log array and this is just going to accept array as a parameter and we're just going to display our vertices for our polygon in the console so within this will create an array vertices and then we're going to use a for loop to loop through the vertices of our polygon so while I is less than the length using the get length method increase the value of I and then we're just going to push a new I'm going to push a new vertex to our array and providing the lat and Lang attributes so we're going to get at the index I and call the LAT method and then the same thing for the longitude so array I and call the longitude method so these functions are pretty self-explanatory but they are a little strange basically where I'm getting these it's following the MVC array structure that the Google Maps API uses if you want to learn more about that special data structure there will be a link in the description to the documentation for that and then lastly we just want to console dot log R vertices all right now all we have left is to run this function when the polygon is being edited so we do this by calling the Google Maps ad listener method and we'll do that within our main Maps function so Google Maps not event ad listener and we're gonna be adding it to our polygons path so we call polygon but we call the get path method on our polygon and then we specify the event that is being tart like the event being fired so it's called set at and that is the event that's fired when you edit one of the polygon vertices and then we supply a callback function and within that callback function we will call our log array function that we wrote passing in the updated path and then finally I'm just going to duplicate this listener and also call it for the insert at event and this is a similar event it's just it this one fires if we add a new vertex to the polygon there's these little side vertices here so if I save that and then we open our console at the bottom and then I edit the vertices we can see that it popped up down at the bottom there so I can expand this and we can see an updated list and if I edit this again once again it gets logged with the updated Latin languor Donets great so we can see that the array of vertices is displayed and you know this is a simple example but again you can imagine applications where you might want the user to be tracing something on the map and you could listen on these events and use this information elsewhere in your page or maybe even in your web app so there are also other lines and shapes that can be used and I will put another link in the description for more details on that so we've reached the end this is all I have for today this has been a small demo of some of the features that Google the Google Maps API has to offer I hope you found my explanation of how to get started and implement some of these things useful if you want to find the code I'll have the code for all four of these examples up on github and please comment and let me know if there's anything more specific you'd like to see done and maybe I could make a follow-up video with more demos if that's useful thanks a lot if you've enjoyed this video please like and subscribe if you want to learn I made another tutorial series recently a few months back about how to develop a simple full stack react app so if you've you know if you've been enjoying the JavaScript code here and you want to go a little bit further with it there's an some interesting development skills you can learn over in that tutorial so and again if there's anything you'd like to see outside of Google Maps or anything else in a future video please let me know take care everybody
Info
Channel: Bryce St. Pierre
Views: 84,459
Rating: 4.9080038 out of 5
Keywords: google, google maps, google maps api, coding tutorial, coding, code, javascript, js, javascript tutorial, web, web development, new 2019
Id: oVr6unKZbg4
Channel Id: undefined
Length: 39min 27sec (2367 seconds)
Published: Sun Feb 24 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.