Map Live User Location using Leaflet.js and OpenStreetMap - JavaScript Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to this tutorial so today what I'm going to be showing you is how you can visualize the current live location of a user using the leaflet.js library and data coming from the openstreetmap project so leaflet.js is a free JavaScript library that allows you to work with some underlying map data so for that we're using openstreetmap but first of all let's focus on getting started with leaflet.js so it's quite easy to get started if you go to the quick start guide there's a CDN link that you can import so you need to import two things first of all some CSS so first of all I'll copy this CDN link to the CSS and place it in the head of my document next I need to place the CDN link to the JavaScript so this has to come after the CSS so I'll place that directly afterwards then I have to create an element with an ID of map in my code so I'll just copy and paste this div that's been created here and place that in the body of my document and I also have to set a height for the map so that it's visible on the page so I'll do that now I'll set that to a little bit larger than they suggest so we can see it clearly 350 pixels so now we've imported everything the next thing to do is to set up the map so the suggested code is this so I'm going to copy and paste this into the script in my HTML document and I'll just explain what's going on here so the library that we've imported it's available under the reference L for leaflip and that has all of the methods that we need on it to create a map and plot a marker so we can see the current location of the user so the first thing we're doing here is initializing a map and specifying that it should appear in the element with an ID of map so in that div I copied in earlier next we're setting the view for the map so in terms of latitude and longitude and the final value here is the zoom and a reference to the map that's being initialized is being saved under the reference of map so you can call methods on Mac now so for example this line of code is quite long we can actually separate this out into two lines of code where I call set view or map on a second line now with this code alone we'll see the user interface for leaflet.js in our document but there's still no underlying map data so we still need to specify where are we getting the Mac data from so we're going to be getting that from open Street View and leaflet.js in the examples it uses uses open Street View as well so this is very simple so you can copy and paste this straight into your code and it will immediately start working so what this code here is saying is to create a tunnel layer and to get that tile layout from the openstreetmap server to a specified zoom level and longitude and latitude and then as the second argument we're specifying a maximum level of zoom and an attribution on the tile layer so I'll leave those both to the defaults and then after that what we're doing is using the add to method to add it to the current map that we just initialized now if we take a look at the document you see that leaflet has retrieved an appropriate tile from the openstreetmap server corresponding to the latitude and the longitude that is set here and also the zoom level so we now have leaflet.js retrieving data from openstreetmap for fixed coordinates but what we actually want is dynamic coordinates that are based upon the current position of a user so to request the current position of a user you can call upon the HTML5 geolocation API which is available under navigator.geolocation and on there are the methods that you need to be able to get the user's current position so the one you want here is watch position because this is going to keep watching the position of a user if you get current position this will just get the user's location once so we want to watch the user's current position so the first argument you need to pass in here is a function that is going to be called every time the user's location updates of course it's also going to run once to get the user's initial location so when coordinates for the user's current position are retrieved the success function is going to fire so I'll Define this here and what you have available to you in that function what will be automatically passed into it is an object that you can call whatever you like I call it pause for position and that's going to have all the information on it about the user's current location okay so I'm going to extract some information from this object first bit of information I want is the latitude of the user the next bit is going to be the longitude of the user so both are available on this property called chords and the final bit of information that I want is the accuracy of the latitude and longitude estimation so that's also available on chords under the property name accuracy so accuracy gives you a value for how good the latitude and longitude estimate is within a number of meters okay so the next thing I'm going to do is to use this information to create a marker on the map and also a circle around that marker giving you a visual representation of the accuracy of the estimation so to create a marker you call the marker method on the leaflet library and you pass in there as an array the latitude and longitude values so we've already saved them in variables and then finally what you want to do is add that to and you want to pass in the reference to the map that we created now for the circle denoting the accuracy it's very similar apart from you call the circle method and you also want to pass in a second argument here after the array which is going to be an object so you want to set the radius of this circle to accuracy so the circle is going to appear at the same latitude and longitude as the marker and it's going to have a radius of a number of meters relating to the accuracy and then of course we're adding that to the map as well now it's actually possible that we can't retrieve this information because the user refuses to let us have access to their current location information so it's important to handle this error appropriately so I'll Define a new error function here and what I have available to me here if there is an error is an error object now if the code on that error object is one this means that the user has refused access to their current location so in this case you might want to alert the user with a message please allow your location access otherwise it's probably a technical error in getting the user's current geo location so in this case you probably want a different message for the user cannot get current location something like that now the final thing to do before testing is we still want to set the zoom of the map to the current location of the marker and the circle because at the moment what's happening is we're setting the view to the coordinates of London on Zoom 13 we're adding a marker and a circle to the map but we're not updating the view to the current location of the marker and the circle so if I refresh here and zoom out you see that there's now a marker and a circle on the map but we're still stuck in the original London view so what we want to happen is for the view to update every time there's information about the user's location and usually you'd want the zoom to be no greater than the radius of the circle which is denoting the accuracy of the user's current position so to set the current bounds of the map you can call the fit bounce method on the map and then you want to call the get bounds method on the circle so for that I want to create a reference to the circle and I'll also create a reference to the marker and I want to get the bounds of the circle so that's going to be the value of the new bounds for the map so if I refresh here you see that we're no longer on the London view the bounds of the map have updated to the user's new live location so this is good as a static representation of the current position of the user but what if the user changes position so if you want to manipulate the position of the user without going for a run what you can do is click on this three dots tab in your Dev tools go to more tools and then down here you'll be able to select sensors and then you can select locations preset locations from a list so if I say now that I'm in Moscow the marker and the circle and also the bounds of the view are now in Moscow if I go to San Francisco you see that it's updating each time but if I zoom out you are going to see that there are several markers on the map now so that's not what we want we want only one marker and one circle on the map representing the user's current location and this can be a problem if you've got more precise tracking so let's say if you've got a running app and users going for a run so let's say they change positions slightly so this is not a kind of behavior you want you only want one marker and one circle on the map at a time representing the user's current location so what I'm going to do to fix this is to declare the marker and the circle outside of the function so that they are in the global scope now instead of declaring two new variables inside the function I'm just going to update the value of those now existing variables and then I'm going to add an if statement before these values are assigned and what this is going to do is to check whether a value already exists or marker so whether a marker already exists on the map so the first time that this function runs there is no value for marker so the code inside the if statement is going to be ignored but subsequently when another marker is added then it's going to be true so before adding a new marker and a new circle to the map what I want to do is to remove the existing ones so I can do that by calling the remove layer on the map and passing in what it is I want to remove so I want to remove the marker and I also want to remove the circle so I don't need to explicitly check also for the existence of a circle because every time a marker is there a circle must also be there okay so let's test this now I'll set the coordinates to let's say Shanghai and let's say I'm going for a run in Shanghai hopefully now when I change the location you see there's still only one marker and one Circle so we're removing the current marker and circle and that's being updated each time with a new one now there are a couple of settings that you might want to play around with here so the first is that there's something of I wouldn't call it a bug but something an unwanted Behavior pass so when you change locations slightly the bounds of the map go back to the circle so you may not want this if if a user's zoomed out and then they change the location slightly they might want to remain at this level of zoom and not go back in to the radius of the circle so to prevent this you want this line of code here running only once initially and then not running again so to prevent that happening more than once I'm going to check the value of a variable called zoomed and I'm going to run this line of code only if there is currently no value for Zoomed and what I'm going to do is to create zoomed up here in the global scope and then save the return value of calling bit bounds to make that the value of zoomed so the first time this function runs no value has been assigned to zoom so the code inside the if statement runs and Bounds are set for the map and at the same time a value is set to assumed so subsequently when this function runs a value is assigned to zoomed which means subsequently the if statement will be ignored and no new bounds are set for the map okay so when I test this now and I zoom out and I change my location and we should still stay at the same level of Zoom so you can see we're staying at the same level of Zoom but we're not following the marker so you might still want to follow the marker so if you want that too then you can say map dot set view passing in the latitude and longitude there and that's all you need to do okay so let's test this out let's go to Tokyo now so I'm going to zoom out on Tokyo now hopefully when I update the position of the user we're going to stay at the same level of Zoom and the center of the map is going to track the marker and the circle so I changed my latitude slightly so that's working as expected we're moving along with the marker in the circle without the level of Zoom changing so if this is tracking a user and they are moving around then the center of the map is always going to be fixated on them and this is probably the kind of behavior that you want so this is how you can map the current location of a user using leaflet.js and openstreetmap for the underlying data so I hope you found this tutorial useful if you did please consider hitting the like button down below because that helps us with the algorithm and others to find the video and if you'd like to see more content like this in the future don't forget you can subscribe to the channel
Info
Channel: OpenJavaScript
Views: 67,880
Rating: undefined out of 5
Keywords:
Id: NyjMmNCtKf4
Channel Id: undefined
Length: 16min 6sec (966 seconds)
Published: Mon Oct 31 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.