【问题标题】:How to get geolocation with Vanilla JavaScript/Ajax - Country and City如何使用 Vanilla JavaScript/Ajax 获取地理位置 - 国家和城市
【发布时间】:2018-01-19 01:27:23
【问题描述】:

我正在学习 JavaScript 和 Ajax。我不想使用任何库或框架。

我找到了一个使用这个的代码:https://codepen.io/Aurelian/pen/VyqemX

我的问题是,如何使用纯 JavaScript 实现这一点?没有 jQuery?

我需要重新学习 AJAX 基础知识,因为我已经很久没有这样做了。

另外,我需要连接到 API 吗?网址部分?其他网站如何获取当前位置?

有类似的问题,但他们都是 jQuery。所以请使用 Vanilla JavaScript。

JS代码:

  jQuery.ajax( {
  url: '//freegeoip.net/json/',
  type: 'POST',
  dataType: 'jsonp',
  success: function(location) {
    // example where I update content on the page.
    jQuery('#city').html(location.city);
    jQuery('#region-code').html(location.region_code);
    jQuery('#region-name').html(location.region_name);
    jQuery('#areacode').html(location.areacode);
    jQuery('#ip').html(location.ip);
    jQuery('#zipcode').html(location.zipcode);
    jQuery('#longitude').html(location.longitude);
    jQuery('#latitude').html(location.latitude);
    jQuery('#country-name').html(location.country_name);
    jQuery('#country-code').html(location.country_code);
  }
} );

【问题讨论】:

    标签: javascript json ajax geolocation


    【解决方案1】:

    我需要连接到 API 吗? URL 部分?

    是的。嗯,有点。 API 通过检查发出请求的 IP 来确定您的位置。它可能会在数据库中查找该 IP 或其他东西以查找其位置。

    因此,如果您想做同样的事情,那么是的,您确实需要连接到 API。这个过程需要的不仅仅是普通的 javascript 和浏览器,而且不能只在客户端完成。

    或者可以吗?.. 话虽如此,可以使用大多数浏览器中可用的geolocation API 在获得用户许可的情况下直接从浏览器检测用户位置。这给出了一个位置坐标(纬度、经度),然后您可以使用 Google Maps API 或类似的东西查看它。

    阅读更多:

    https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

    https://developers.google.com/maps/documentation/geocoding/start#reverse

    我需要重新做 AJAX 基础知识,因为我很久没做过了。

    不一定!现在大多数浏览器都支持fetch API,这使得执行 AJAX 请求等变得更加容易。

    https://caniuse.com/#feat=fetch

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    祝你好运!

    【讨论】:

    • 如何转换经纬度?我相信这些数字存储在谷歌和其他公司拥有的数据库中,因此他们可以确定位置。所以换句话说,我们需要让 API 正确吗?谷歌教程很奇怪 xd 我被这个 xd 弄糊涂了
    猜你喜欢
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2016-12-17
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多