I'm building a React weather app with an API that only accepts a Latitude and Longitude, not a city name. I'm new to React and am wondering if there's a way to transform the user input (City name) to latitude and longitude so I can call the api.
Thank you!
I'm building a React weather app with an API that only accepts a Latitude and Longitude, not a city name. I'm new to React and am wondering if there's a way to transform the user input (City name) to latitude and longitude so I can call the api.
Thank you!
Share Improve this question asked Oct 11, 2022 at 19:33 E6ixE6ix 561 silver badge4 bronze badges 1- Does your question specifically asks about geocoding using Google Maps API? – Yrll Commented Oct 11, 2022 at 23:22
3 Answers
Reset to default 4You should try a geolocation package or api like this one for example: https://www.npmjs./package//react-geocode
They've already done the busy work of figuring out that conversion for you.
There are few other Apis I have used for weather applications which use city name to fetch weather data along with latitude and longitude.you can take a look if it serves your purpose.
Open weather map api
Accu weather Api
Below code will display user's geolocation.
Please don't hesitate to use values of lat
and long
.
const [lat, setLat] = useState(null);
const [long, setLong] = useState(null);
const geolocationAPI = navigator.geolocation;
const getUserCoordinates = () => {
if (!geolocationAPI) {
console.log("Geolocation API is not available in your browser!");
} else {
geolocationAPI.getCurrentPosition(
(position) => {
const { coords } = position;
setLat(coords.latitude);
setLong(coords.longitude);
codeLatLng(coords.latitude, coords.longitude)
},
(error) => {
console.log("Something went wrong getting your position!");
}
);
}
};