从经纬度获取国家/地区

发布于 2024-10-08 14:18:29 字数 150 浏览 2 评论 0 原文

我想知道如何从纬度和纬度获取国家/地区名称使用 JavaScript 计算经度。我愿意使用 Google 地图的 JavaScript API。我还可以获得城市和邮政编码吗?

编辑:我的目标是自动填写地址字段,而不是将其显示在地图上。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

ゞ花落谁相伴 2024-10-15 14:18:30

Google Geocoding API 以 JSON 格式提供这些结果。它有免费套餐,但您需要为无限制的 API 请求付费。

请求的 API 链接如下所示:

'https://maps.googleapis.com/maps/api/geocode/json?latlng=11.2742848,75.8013801&key=YOUR_API_KEY_HERE'

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'
尛丟丟 2024-10-15 14:18:30

如果需要一个独立的库(即没有服务器/互联网连接,并且速度快),并且只需要国家/地区信息,则以下基于 openstreetmap 数据的库可能会很有用 - 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) { ... });

使用 code(latlng 的国家/地区代码)调用回调。

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.

白云悠悠 2024-10-15 14:18:30
<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>
<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>
长发绾君心 2024-10-15 14:18:30

如果您只需要基于坐标(lat、lng)的国家/地区信息,您可以使用 cocod_to_country npm 包。这样你就不需要制作任何API。它基于 OSM 国家边界。

编辑:

值得注意的是coefficient_to_country< /strong> npm 包相当重,导致客户端效率问题。这是由于 @osm_borders/maritime_10m 依赖包。

因此,如果您不需要在坐标查找中包含所有国家/地区,则最好使用 geojson-geometries-lookup npm 包和您需要的国家/地区的自定义 geojson 文件。

另一种选择是使用较低分辨率的国家/地区形状文件来减小文件大小 - 这可能会影响准确性。

这是一个下载 geojson 国家/地区形状的自定义选择的网站:https://osm-boundaries.com/


否则,如果您需要更多位置信息(城市、地址、社区等),您可以探索各种地理编码 API,例如:

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:

柳絮泡泡 2024-10-15 14:18:30

是的,您可以使用谷歌地图查找给定纬度和经度的国家/地区。使用反向地理编码服务

您可以从服务器收到的响应中获取国家/地区、城市、邮政编码和完整地址。查看链接中的示例以了解详细信息;)

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 ;)

任性一次 2024-10-15 14:18:30

如果您使用 golang,您可以使用这 2 个库之一来获取国家/地区,您甚至不需要进行 api 调用,因为数据集是内置的,因此它是无限的。

https://github.com/SocialHarvest/geobed

https://github.com/bradfitz/latlong

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

纵性 2024-10-15 14:18:30

您可以通过以下方式实现:https://www.weatherapi.com/ 免费。

我的演示是在 React 中一步步进行的,但是你可以用任何你想要的方式来完成,关键是这个 Weather API,它接受 LON 和 LAT 作为字符串来生成城市和天气信息 ->
https://api.weatherapi.com/v1/forecast.json?key=YOUR-KEY&q=LATITUDE,LONGITUDE&days=1&aqi=no&alerts=n

注意:您将通过注册生成您自己的密钥

为此,您将需要 4 个状态:

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

获取纬度和经度 + 弹出窗口

首先:通过使用此代码并设置状态,请求用户访问“位置”(这将有一个弹出窗口)到纬度和经度。

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();
}, []);

根据纬度和纬度获取城市/国家/地区Lon:

第二次使用 https://www.weatherapi.com/ API 获取城市和其他情报,基于纬度和经度

API 看起来像这样: https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=53.3498053,-6.2603097&days=1&aqi=no&alerts=n

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

现在通过纬度和经度调用此 API 来获取位置数据,包括城市。我使用 useEffect 作为触发器,因此一旦获得有关 Latitude 的信息,我就会使用 axios 调用 api,并将 City state 设置为来自 api 对象的内容。

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]);

这是我的 YouTube 频道的视频,您可以在其中观看演示:https://youtu.be/gxcG8V3Fpbk

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"
},

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"
},
终遇你 2024-10-15 14:18:30

无需 API 密钥

文档

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

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";
}
滴情不沾 2024-10-15 14:18:29

我不知道它是否适用于谷歌地图,但有一个网络服务可以返回国家/地区代码并以纬度和经度作为参数。

这是一个例子:
http://api.geonames.org/countryCodeJSON?lat =49.03&lng=10.2&username=demo

返回JSON数据:
{"languages":"de","distance":"0","countryCode":"DE","countryName":"Germany"}

我还发现了一些描述:

任何给定点的 ISO 国家/地区代码。

  • 网络服务类型:REST
  • 网址:ws.geonames.org/countryCode?
  • 参数:latlng类型lang半径 (沿海地区最近国家的缓冲区(以公里为单位)
  • 结果:返回给定纬度/经度的 ISO 国家/地区代码

使用参数type=xml,此服务返回带有 iso 国家/地区代码和国家/地区名称的 xml 文档。可选参数 lang 可用于指定国家/地区名称应使用的语言。JSON 输出由 type=JSON

生成

请参阅 docs

编辑: 请注意,demo 只是演示用户,您应该创建http://www.geonames.org/login 上的用户帐户才能使用该服务。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文