API (https://ipapi.co/json) used in local weather app not showing correct location


Since codepen switched to HTTPS in summer, I changed my local weather app to use the API https://ipapi.co/json to retrieve latitude and longitude for my current location to query local weather info. It has been working great.

However, to my surprise today, the API is retrieving wrong city, latitude and longitude even though it returned correct IP address when I ran https://ipapi.co/json on browser. With the wrong city, the local weather app is getting wrong information.

Does anyone here know why the API is getting wrong city information ?

Services like the one you’re using rely on data from your internet connection. This information can be confounding for a variety of reasons beyond your control. You won’t get an accurate reading unless you use the native geolocation API, which there’s no reason to avoid.

Can you enlighten me what native geolocation API i can use, please ?


Yeah, sure. It’s really straight forward and you can probably find working examples on the forum here with a search. Here’s the MDN docs:

This is the essence:

if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(function(position) {
      do_something(position.coords.latitude, position.coords.longitude);
} else {
  /* Show an error for the user that geolocation is not available */

Thanks. This requires explicit permission to get location information. How is this going to work from within the app ?

A pop up quickly asks the user if they give permission. It’s a default browser behaviour, so you don’t have to program that :slight_smile:

I made a Codepen to demo this some time ago:

getCurrentPosition takes a second callback which will fire if the user has denied permissions, or there is some other error getting coordinates.

Ok, this is doable, although this won’t get me city and region name. I can plug in the longitude and latitude to open weather app api to get city name and country name instead. How do I make the browser automatically get the geolocation without having to click a button though ?

It’s a one-time permission. It’s a security feature built into modern browsers to stop websites snooping on user location without their consent.

Thank you. I changed my code and got it working again.

I don’t know why this API https://ipapi.co/json which used to get correct city location based on IP address now displays ISP location, regardless of IP address.

I ran it on my wireless phone network, got correct IP address but had Seattle as the city. When I switched to my home network, still same IP address, but got Chicago as the city. This is nut. This API is useless now.