Track your location with the JavaScript Geolocation API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone today we're gonna build something super cool we're gonna have two pages the first page is gonna be tracking our location our geolocation on our phone as we take a walk or as we cycle and then we're gonna collect this data and draw it on map using map box so let's get started we'll start by creating a new folder called map tracking and inside this folder we're gonna have a tracking dot HTML page and then for later on we are gonna need an index of HTML and an app dot UJS let's open this with visual studio code and then let's serve it using npx HTTP server too now let's go back to the browser and open this localhost port 8080 open left tools console and now we're gonna go into the tracking dot HTML page the first page we're gonna build tracking dot HTML is going to use the Navigator geolocation API which is an API that allows us to get the position the GU position using the GPS of the person that's gonna be either using their laptop or maybe using their phone and we're gonna collect all of these in an array and save it a local storage so that later on we can read it and draw it on a map so we're gonna start with the boilerplate we have and I'm using that from emmet I'm gonna call this one tracking location and that's gonna have two buttons one to start the tracking and then another one to stop I'm gonna give these two different ideas start and stop and we're not gonna write a lot of JavaScript code so I'm gonna make it in line over here just for simplicity and I'm gonna grab reference to both of these so that's gonna be const start and stop equals and we use query selector to find them by ID from the dom and then we're gonna add an event listener on this start button so when we click on it what do we want to do when we click on the button what we're gonna do here is we're gonna call the geolocation API so that's gonna be in navigator dot geo location and then we have two methods I'm gonna start with the get current position and this get current position accepts a success callback so what are we going to do once we get a response from the GPS server we can console.log it and then if there is an error we pass in an error callback over here so error and I'm just gonna console.log it and then finally we can pass in some options let's just pass nothing for now and try it in the browser let's go back reload and now we have the start and stop button we click on the start notice how to ask us that the browser wants to know your location I want to talk about two important things here one never asked for geolocation on page load because no one's gonna accept that it just doesn't make sense why is does this page wanna ask for my permission ideally over here we would have some graphics a little bit of text that explains to this user that the point of this app is to collect the data so that later on we can draw it on a map and then to the geolocation API only works on HTTPS so if your website is on HTTP it will not work however localhost is an exception so that's great we don't have to worry about creating is an SSL certificate for our localhost so now that I love the location we're gonna wait a few seconds and then boom we have a location I'm not gonna expand this to not reveal my location but do know that if you are on a laptop you will most likely be on a laptop encoding this which means you're most likely gonna be indoors this could take several seconds because when you're indoors it's hard to reach GPS signal but once you deploy this and you run this on your phone and you are outdoors most of the time is going to be faster to reach the GPS signal which means you will get a location faster now if I take my laptop and then move this is not going to update because this is a single call to get current position sometimes you might be interested in getting location changes and for that we have a different method but only use that method if you're really offering something that has to do with location that changes because it's gonna drain the battery let's take a look at how we can use it so instead of get current position I can ask for watch position and that's gonna call my callback every single time the browser thinks that my location has changed so now let's go back to the browser reload it I want to show you how this work but without revealing my location and also I want to move but I cannot take the camera with me so I want to show you how it shows you the updates and luckily there's a tool that helps us with that in dev tools so I'm gonna press command shift P or ctrl shift P and I'm gonna open these sensors show sensors and over here I'm gonna click Berlin and that's gonna set my location to Berlin so now if I start notice that we don't get a prompt anymore because we already allowed localhost to see our location so now this is what we get back we get a data with a chords object which has the latitude and the longitude and the accuracy I think this is probably meters but I'm not a hundred percent sure now what if I change my location of course it doesn't have to be a dramatic change maybe you can add it to over here and then we get another update saying that the location has changed I can also choose Paulo I can also choose other cities and then yeah you can see how it's updating since I'm gonna be going out in cycling I do want to get high accuracy positions so you can ask the browser to give you high accuracy positions by turning on the high accuracy flag if you just scare about rough data then it's better not to turn it on because this is gonna drain the battery so you can specify this as the third argument so again watch position takes the success takes the error and then we can enable enable high accuracy and that's going to be true now that we have the data we want to store it in a local storage so that later on when I'm back from cycling I can show it on a map so I'm gonna create an array of coordinates and then every time I get a response back I'm gonna push to that array so coordinates that push I'm gonna push the data dot code words dot the latitude and the data dot chords not longitude finally I need to save that and local storage and the local storage API is a synchronous storage which means it could be slow if you use it very often in this particular example we don't really care about performance is just toi up it allows us to store keys and values but both of them are strings which means if you want to save an object like an array we cannot save it as is we have to json stringify it first that's because jason string if i is going to convert it from an array into a string which is then compatible with local storage so let's go ahead and call local storage that set item and that's going to be coordinates and then we cannot immediately save coordinates we have to call json dot stringify and then coordinates and I'll reload the page start and if we inspect the local storage dot get our item coordinates we will have some of the coordinates saved over here which is great then if you want to get the array out of that we just called JSON data parse which does the opposite of json stringify and we will get an array of the coordinates of course as you move you will start getting more and more positions so that's it for now I'm gonna go out and cycle a little bit with my phone running this up make sure you are on HTTP or else the geolocation will not work and also one more thing your phone will turn off the screen after 30 seconds or one minute and we cannot keep it on there is something called wait clock but it's not available in browsers yet so one of my friends is actually working on that API the wakelock api his name is Kenneth from Denmark and I think it just landed in chrome beta so we cannot really use it right now it's not supported on all browsers so what I'm just gonna do is I'm gonna change the settings from my phone and make it not turn off the screen for 30 minutes just a temporarily hack hopefully in a couple of months or maybe a couple of years we can use this API I wanted to make sense so let's go cycling and I'm back from cycling well of course I did the cycling part first and now I'm recording both videos at the same time but I lowered the camera so you think that it was a different scene anyway we have the data on my phone over here and we need a way to transfer to my computer and this is why we need a cable I'm going to plug that cable in my computer and I'm gonna plug it in my phone and now we can go to Chrome colon colon slash inspect and I'm gonna see my phone over here for this to work you need to have an Android device you can do the same on iOS but then you have to use Safari and then too you need to enable USB debugging and you have to accept the prompt on your phone to trust your computer and then I click inspect and now I have an inspector running for this page which I have accidentally reloaded but that's not a big deal because remember we had the data in our local storage so if I click on local storage I will have the list of all the coordinates over here I can read them with local storage dot coordinates but it's gonna give me the string so then I need to Jason dot parse it and this is gonna give me the object over here so I collected around 200 data points that's great while I was cycling but the last step is I need to copy this to my computer and and I cannot copy it like this this doesn't work unless you want to reformat it later on look chrome dev tools and I think other dev tools have this copy command over here which is gonna copy it into my clipboard so if I show you my clipboard over here you can see this is what I just copied here and now I can close this I'm done with it and I can go back and I can go back to visual studio code paste it over here scroll all the way to the top and these are all the data points that I have collected so just before we get started I realized actually I did it on purpose we have saved the data in latitude and then longitude whereas map box expects longitude and then latitude this is not a big deal but this is an opportunity for me to show you some cool tricks in your editor you can do them in vs code however I like to do them in sublime text even though I use vs code for day-to-day things but all the transformations when I have a lot of data I do them on sublime text so let's copy all of this open sublime text based and go all the way to the top and now what I want to do is I want to find every longitude and then switch it and luckily here the latitude and longitudes are really different so I can choose all the four ones and the net and then select them but let's say you cannot what we can do is we can select the closing bracket so select one of the closing brackets and then hit command D several times or control D on non mark computers and then all the way on to the end and now scroll back to the top and I'll move the cursor left left left and we are on the longitude I can press command control up or control shift up on normal computers and that's gonna push the line to the top right the comma so that the array stays involved format and that's it I just switched the latitude and longitude and just to make sure you know about my courses learn JavaScript online you can learn modern JavaScript over here you can take your own notes and you will come back here and be able to solve your own challenges I think you're gonna love them if you're enjoying this channel you're definitely gonna enjoy these courses and I also have now a react course so that's going to be on react - tutorial dot out and you will learn react step-by-step in a highly interactive environment I can show you some of the lessons over here this is it this is one of the lessons and you can see this is one of the projects where you build your online store where you can log in at the amount of products that you want to buy and log out and I think you're really gonna enjoy this course now let's copy this this is going to be the data that we're going to use in the other file and the index.html where we're gonna have the mob drawing our path so let's get started with this and say map and then we're gonna use a script and that's gonna be pointing to the out of GIS and I'm gonna give it type module if you're not sure about this type module or map make sure to check out my previous video which is linked somewhere at the top and then let's create a div with an ID map perfect and go into the apogee s and let's just save our coordinates so this can be concern it's these are all the coordinates and now let's go to the top we will need to import map box so let's go to my box first click on web and then we will use the map box at the end we need the Stars copy the Stars put them in the index dot HTML and then copy the script tag and that's something we can import here at the top and now finally we need the HTML and some of the stars but as usual I like to make the map full screen so let's do it ourselves in a style over here that's gonna be the map is gonna have a width of 100 V W so viewport width and a height 100 th viewport height and let's reset the margin on the body and now this is the code we need to start with the map remember that I will be resetting my token circle so you cannot use my token you have to create your own change this to Const and this is gonna match the idea we have an HTML and when we go next this is where we want to look for something similar to our example and that's it here are the GU Jason line click on it and we have an example that you can see here is this what you're trying to do yes that's exactly it we want to have a list of coordinates and from that we want to draw the the lines on the map so we have the map creation that's all being taken care of we can copy all of this code and I'll explain it paste it over here and that's starting with a map dot onload we add a new source of data which we're gonna call route or route you can call it wherever you want the type of it is a geo jason and it's a line string because you've got other you've got several types of to JSON geometry and this is where you have to give it the list of coordinates longitude and then latitude and then you add this layer to the map and this is where you can specify how it looks like the color maybe we'll play around with these at the end I would always go back to the browser see if the sample usage works before customizing it so let's go back reload the page and actually go back to the index.html this time and scroll up and zoom in on San Francisco instead of zooming in a lot we can just go back and copy the same Center and the zoom level and yes this is it we're already drawing it now we can just go back and it's gonna be as easy as getting rid of all of that and replacing it with coordinates because we already have the coordinates in a variable at the top then I'm gonna use one of the points in the middle as the center so that we can actually see our map we don't want to focus it on San Francisco we wanna focus on Amsterdam and I'm rid of the page and that's it we were able to take the coordinates that we recorded from our phone draw it on the map and you can also customize this even more you can make it draw the map live it's just really interesting to do to be able to do these kind of projects that don't take a lot of time I hope you enjoyed this video and I'll see you next week don't forget to check out clear in JavaScript that online or even if you want to learn react react tutorial dot out they're both linked in the description below and I'll see you soon
Info
Channel: Jad Joubran
Views: 22,382
Rating: undefined out of 5
Keywords: javascript, geolocation, modern web, tutorial, fun
Id: 4SkIpVRyn_w
Channel Id: undefined
Length: 17min 54sec (1074 seconds)
Published: Tue Mar 17 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.