Home > Article > Web Front-end > JS gets user's current location
This time I will bring you JS to get the user's current location. What are the precautions for JS to get the user's current location? The following is a practical case, let's take a look.
The following code is shared with everyone in js to get the city where the user is 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('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js',function(){ alert(remote_ip_info.country);//国家 alert(remote_ip_info.province);//省份 alert(remote_ip_info.city);//城市 }); </script>
JS to get 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>Believe it After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website! Recommended reading:
Detailed explanation of the use of vue event mechanism
How AngularJs prevents XSS attacks
AngularJS uses Filter to customize filter case details
The above is the detailed content of JS gets user's current location. For more information, please follow other related articles on the PHP Chinese website!