Latitude + Longitude = city name, React JS

4.8k Views Asked by At

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!

3

There are 3 best solutions below

1
Jet.B.Pope On

You should try a geolocation package or api like this one for example: https://www.npmjs.com/package//react-geocode

They've already done the busy work of figuring out that conversion for you.

1
saikumar305 On

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.

  1. Open weather map api

  2. Accu weather Api

0
cocoa On

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!");
        }
      );
    }
  };