如何使用Vanilla JavaScript / Ajax获取地理位置 - 国家和城市

时间:2018-01-19 01:27:23

标签: javascript json ajax geolocation

我正在学习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);
  }
} );

1 个答案:

答案 0 :(得分:0)

  

我是否需要连接到API?网址部分?

是。好吧,有点儿。 API通过检查请求的IP来确定您的位置。它可能会在数据库中查找IP或查找其位置。

所以如果你想做同样的事情,那么是的,你需要连接到API。这个过程需要的不仅仅是vanilla 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

祝你好运!