最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Latitude + Longitude = city name, React JS - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 4

You 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.

  1. Open weather map api

  2. 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!");
        }
      );
    }
  };
发布评论

评论列表(0)

  1. 暂无评论