1. 58
    Add a Button that Finds your Location and Navigates the Map to the Location with Leaflet
    47s

Add a Button that Finds your Location and Navigates the Map to the Location with Leaflet

Colby Fayock
InstructorColby Fayock
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

Rather than setting a location manually, web browsers provide a way that we can request access to someone's location. This lets us personalize features and particularly in our use case, find where the person is on the map to see what's close to them.

Click here for exercise instructions

Colby Fayock: [0:00] To add a new button, we're going to first copy the one that we had before and add it right below. Instead of the "Set location" statement, we're going to say, "Find my location." Inside of this handle function, we're going to create a new one called handleOnFindLocation.

[0:11] The first thing we need to do is actually define that function. We're going to say, "Function handleOnFindLocation." Because we're going to use our map again, we can copy and paste that block from above where we de-structure our map. Now that we have our map, we're going to make use of its geolocation features.

[0:24] We're going to set our map, and we're going to tell it to locate. Now, when we reload the page, we can see our "find my location" button. When we click it, we can see that the browser is asking for our location.

[0:32] If we click Allow, we can see that it's actually not doing anything. When using the locate feature, it doesn't do anything except find the location. We can pass in an options object where we can specify setView(true). Now, next time we click "find my location" and we allow it, it finds our location.