Get GeoLocation API
I needed to get the coordinates of the user so I was recommended to use MDN Geolocation API that gets me the coordinates of where I am from my server.
It is actually very simple but I will be coding it in React.js so there’s a little change in the code from the MDN doc.
Within the Class Component
write a method getGeolocation()
.Within the function, we want to know if the browser supports this geolocation API or not. We are going to do that we are going to write an if
state
How to return coordinates?
From the MDN doc, you can simply use the getCurrentPosition()
This initiates an asynchronous request to detect the user’s position, and queries the positioning hardware to get up-to-date information
In other word, getCurrentPosition()
will detect the user’s position.
You can view your position in your console to check your coordinates
Render the coordinates on web
Now that your coordinates are showing in your console, you want it to show up on the actual web page (UI). Depending on where you want it to show up, let’s create a paragraph <p>show my coordinates</p>
tag as a placeholder.
Step 1: set the initial state in your Class Component
where you have your getGeoLocation()
method
I have set my state location
as null
meaning that my initial location state will not have a data yet
Step 2: change the initial state by storing the coordinates data. In the getGeoLocation()
method, put this.setState({})
after console.log(latlng)
Step 3: Render out the location in the Class Component
render se
location = { this.state.location }
Step 4: Update your <p>
paragraph tag by passing in the props