Home > Web Front-end > JS Tutorial > JavaScript gets the city and geographical location of the user

JavaScript gets the city and geographical location of the user

不言
Release: 2018-04-21 16:41:16
Original
2389 people have browsed it

This article mainly introduces the example code of JavaScript to obtain the city and geographical location of the user. It is very good and has reference value. Friends who need it can refer to it.

The following code is shared with everyone in js to obtain users. The city where you are located, the specific code is as follows:


<!doctype html> 
<html lang="en"> 
 <head> 
 <meta charset="UTF-8"> 
 <title>获取用户地理位置</title> 
 <script type="text/javascript" src="./jquery-3.3.1.js"></script> 
 </head> 
 <body> 
 </body> 
</html> 
<script> 
$.getScript(&#39;http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&#39;,function(){  
 alert(remote_ip_info.country);//国家  
 alert(remote_ip_info.province);//省份  
 alert(remote_ip_info.city);//城市  
});  
</script>
Copy after login


JS gets the user’s geographical location


<script type="text/javascript">
  var x = document.getElementById("x");
  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
      x.innerHTML = "该浏览器不支持定位功能!";
    }
  }
  function showPosition(position) {
    x.innerHTML = "纬度:" + position.coords.latitude + "\n经度:"
        + position.coords.longitude;
  }
  function showError(error) {
    switch (error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "用户拒绝对获取地理位置的请求。";
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "位置信息是不可用的。";
      break;
    case error.TIMEOUT:
      x.innerHTML = "请求用户地理位置超时。";
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "未知错误。";
      break;
    }
  }
  getLocation();
</script>
Copy after login

Related recommendations:

JavaScript to get HTTP information in the navigation bar example sharing


The above is the detailed content of JavaScript gets the city and geographical location of the user. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template