Get country from latitude longitude
Asked Answered
U

9

74

I would like to know how I can get the country name from latitude & longitude using JavaScript. I am open to use of Google Maps’ JavaScript API. Can I also get city and zip?

Edit: My aim is to fill up the address field automatically, not to display it on a map.

Unidirectional answered 21/12, 2010 at 9:15 Comment(2)
R
81

I don't know if it works with google maps, but there is a web service that returns a country code and takes as parameters the lat and long.

Here is an example:
http://api.geonames.org/countryCodeJSON?lat=49.03&lng=10.2&username=demo

Returns a JSON data: {"languages":"de","distance":"0","countryCode":"DE","countryName":"Germany"}

I also found a little description:

The iso country code of any given point.

  • Webservice Type: REST
  • Url: ws.geonames.org/countryCode?
  • Parameters: lat, lng, type, lang, radius (buffer in km for closest country in coastal areas)
  • Result: returns the iso country code for the given latitude/longitude

With the parameter type=xml this service returns an xml document with iso country code and country name. The optional parameter lang can be used to specify the language the country name should be in. JSON output is produced with type=JSON

See the docs

Edit: Please note that demo is just a demonstration user and you should create a user account at http://www.geonames.org/login in order to use the service.

Rubberize answered 21/12, 2010 at 9:20 Comment(8)
This web service took 17 seconds to respond to the example request. It is not reasonable to use such a slow service for a synchronous UI.Barrus
Maybe the server was slow when you checked. I checked just now and yesterday: Both times it responded instantly.Rubberize
Throttles after 2,000 requests.Luannaluanne
You should use the premium api ( api.geonames.org ) for faster response... the WS* is really slow ..Holbert
If someone else (like me) has problems with comparing the result to some constants, please notice that there is a newline character after the ISO code.Manipur
@DanCiborowski-MSFT It's free up to 30,000 daily and 2,000/hour geonames.org/exportApperception
geonames is deadDemarcusdemaria
I somehow don't receive the registration emailBourque
A
20

Google Geocoding API provides these results in JSON format. It has a free tier but you will need to pay for unlimited requests to the API.

The API link to the request will look like this:

'https://maps.googleapis.com/maps/api/geocode/json?latlng=11.2742848,75.8013801&key=YOUR_API_KEY_HERE'
Awry answered 5/12, 2015 at 9:3 Comment(5)
What do you mean by unlimited access?Devonadevondra
The Google Maps Geocoding API has some limitations for free usage. such as maximum free requests per day is 2,500. and maximum free request per second is 10. for more details you can visit developers.google.com/maps/documentation/geocoding/usage-limitsAwry
Does not work unless there are points of interest near the coordinate. If not, then nothing is returned.Zebapda
It doesn't work anymore. See: { "error_message" : "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to g.co/dev/maps-no-account", "results" : [], "status" : "REQUEST_DENIED" }Flinger
I updated the response as of November 2019. You must add your API KEY to the URL to hit the API endpoint.Cutlerr
A
12

If a self-contained library (i.e. no server / internet connection, and fast) is desirable, and only country information is required, the following library based on openstreetmap data can be useful - https://github.com/hlaw/codegrid-js

<script type="text/javascript" src="[path]/codegrid.js"></script>
grid = codegrid.CodeGrid(); // initialize

grid.getCode (lat, lng, function (err, code) { ... });

The callback is called with code, the country code for the latlng.

Acerbic answered 20/9, 2015 at 17:41 Comment(4)
How can you get this working without a server when the javascript can't read the json files locally?Thorlay
wish I could get this to work, but that means you need to include all the tiles and worldjson.Yance
Hallelujah! A solution that doesn't require some shaky "free" geolocation serverDemarcusdemaria
@headduck I'm getting a CORS error when I do this? Any idea on what I can do?Nibble
C
8
<form id="form1" runat="server">
<div>
    <script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
    <br />Country Code:
    <script type="text/javascript">document.write(geoip_country_code());</script>
    <br />Country Name:
    <script type="text/javascript">document.write(geoip_country_name());</script>
    <br />City:
    <script type="text/javascript">document.write(geoip_city());</script>
    <br />Region:
    <script type="text/javascript">document.write(geoip_region());</script>
    <br />Region Name:
    <script type="text/javascript">document.write(geoip_region_name());</script>
    <br />Latitude:
    <script type="text/javascript">document.write(geoip_latitude());</script>
    <br />Longitude:
    <script type="text/javascript">document.write(geoip_longitude());</script>
    <br />Postal Code:
    <script type="text/javascript">document.write(geoip_postal_code());</script>

</div>
</form>
Corked answered 1/3, 2012 at 7:31 Comment(1)
Doesn't seem to be working, since the j.maxmind.com/app/geoip.js script isn't loading anymore.Porterporterage
A
5

Yes, you can use google maps to find the country for given latitudes and longitudes. Use the reverse geocoding service.

You can get the country, city, zip code and the complete address from the response you get from the server. Check the example from the link for details ;)

Adjourn answered 21/12, 2010 at 9:32 Comment(0)
L
4

In case you only need the country information based on coords (lat, lng), you can use the coordinate_to_country npm package. This way you don't need to make any API. It is based on OSM country boundaries.

EDIT:

It worth to note that the coordinate_to_country npm package is quite heavy, causing a efficiency issues on the client-side. This is due to the ~50Mb geojson file in the @osm_borders/maritime_10m dependent package.

Therefore, if you don't need all countries included in your coordinates lookup, you are better off using geojson-geometries-lookup npm package and a custom geojson file of the countries you need.

Another alternative is use a lower resolution country shapes file to reduce file size - this can compromise accuracy.

Here is a site to download custom selection of geojson country shapes: https://osm-boundaries.com/


Otherwise, if you need more location information (city, address, neighbourhood etc.) you can explore various geocoding API's such as:

Livre answered 22/2, 2023 at 15:16 Comment(0)
M
0

If you are using golang you can use one of these 2 libraries to get the country and you don't need to even need make an api call as the data set is inbuilt so its unlimited.

https://github.com/SocialHarvest/geobed

https://github.com/bradfitz/latlong

Matadi answered 3/6, 2016 at 12:15 Comment(0)
T
0

You can do it with: https://www.weatherapi.com/ its FREE.

My demo is in React and step by step, but you can do it in any way you want, the key is this Weather API, that accepts LON and LAT as a string to produce city and weather info -> https://api.weatherapi.com/v1/forecast.json?key=YOUR-KEY&q=LATITUDE,LONGITUDE&days=1&aqi=no&alerts=n

Note: you will to generate YOUR OWN KEY, by signing up

You will need 4 states for this:

const [userAllowedLocation, setUserAllowedLocation] = useState(true);
const [latitude, setLatitude] = useState("");
const [longitude, setLongitude] = useState("");
const [city, setCity] = useState("");

get Lat and Lon + pop up

First: Request access to 'location' from user (this will have a POP-UP), by using this code and set state to Latitude and Longitude.

useEffect(() => {
    function getPosition() {
        const successCallback = (position) => {
            console.log(position);
            setLatitude(position.coords.latitude);
            setLongitude(position.coords.longitude);
            setUserAllowedLocation(true);
        };

        const errorCallback = (error) => {
            setUserAllowedLocation(false);
            console.log(error);
        };

        navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
    }

    getPosition();
}, []);

Fetch City / Country based on Lat & Lon:

Second use https://www.weatherapi.com/ API to get City and other intel, based on Lat and Lon

API looks like this: https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=53.3498053,-6.2603097&days=1&aqi=no&alerts=n

API with explanation: https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=LATITUDE,LONGITUDE&days=1&aqi=no&alerts=n

Now call this API with latitude and longitude to get location data, including city. I am using useEffect as a trigger, so as soon as I get info on Latitude I call the api using axios and set City state to what ever comes out of the api object.

useEffect(() => {
    if (latitude === "" || longitude === "") { // this is to stop fetching data on component mount, cause we have no Latitude and Longitude YET
        return;
    }

    async function getWeather() {
        let res = await axios.get(
            `https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=${latitude},${longitude}&days=1&aqi=no&alerts=no`
        );
        console.log(res.data);
        console.log(res.data.location.name);
        setCity(res.data.location.name);
    }
    getWeather();
}, [latitude, longitude]);

Here is video to my youtube channel, where you can see a demo of this: https://youtu.be/gxcG8V3Fpbk

RESULT from API:

"location": {
"name": "Dublin",
"region": "Dublin",
"country": "Ireland",
"lat": 53.35,
"lon": -6.26,
"tz_id": "Europe/Dublin",
"localtime_epoch": 1673737376,
"localtime": "2023-01-14 23:02"
},
Transcendental answered 14/1, 2023 at 23:43 Comment(0)
M
0

No API Key needed

Documentation

export default async function findCountry({lat, lon}) {
  let data = null;
  try {
  const resp = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json`);
  data = await resp.json();
  } catch (e) {
    data = { address: { country: "Unknown" }}; // default to unknown
  }
  return data.address?.country ?? "Unknown";
}
Marleenmarlen answered 19/4 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.