警报问题 - 使用 haversine 距离公式进行地理定位

Alert issue - Geolocation using harvesine distance formula

我一直在通过 Nikil Abraham 的 Coding for Dummies 学习代码。 书中有一个包含代码的项目,用于为一家餐厅开发一个应用程序,该应用程序可以在距离餐厅 5 到 10 分钟的步行路程内向客户发送提醒,并在点击签到按钮后提供餐厅的优惠券。

我已经通过 codepen 使用 html、css 和 javascript 输入了所有代码,但由于某种原因不会弹出警报。

我已经研究了我可能出错的地方,但我真的卡住了。

代码如下:

Html:

<head>
<title>McDuck's App</title>
</head>
<body>
<h1>McDuck's Local Offers</h1>

<button onclick="getLocation()">CheckIn</button>

<div id="geodisplay"/>
<div id="effect"/>


</body>

Css:

body {
text-align: center;
background: white;
}

h1, h2, h3, p {
font-family: Sans-Serif;
color: black;
}

p {
font-size: 1em;
}

javascript:

function getLocation() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showLocation);
}
}

//门店地址

function showLocation(position){
var mcduckslat=53.510207;
var mcduckslon=-6.399289;

//当前位置

var currentpositionlat=position.coords.latitude;
var currentpositionlon=position.coords.longitude;

//计算当前位置与麦当劳位置的距离

var distance=getDistanceFromLatLonInMiles(mcduckslat, mcduckslon,    
currentpositionlat, currentpositionlon);

//displays the locaton using .inner.HTML property and the lat & long     
 coordinates from your current location

document.getElementById("geodisplay").inner.HTML="Latitude: " +      
currentpositionlat + "<br>Longitude: " + currentpositionlon;

 }

 //haversine distance formula

   function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
   var R = 6371; //Radius of earth in km
   var dLat = deg2rad(lat2-lat1); 
   var dLon = deg2rad(lon2-lon1);
   var a =
   Math.sin(dLat/2) * Math.sin(dLat/2) + 
   Math.cos(deg2rad(lat1)) *                             
   Math.cos(deg2rad(lat2)) *     
   Math.sin(dLon/2) * Math.sin(dLon/2);

 var c = 2 * Math.atan2(Math.sqrt(a),
           Math.sqrt(1-a));
 var d = R * c * 0.372823; //Distance in miles                                        
 return d;
}

function  deg2rad(deg) {
  return deg * (Math.PI/180);
}

alert(distance);

if (distance < 0.5) {
 alert("You get a free meal");
}
else {
 alert("Thanks for checking in!");
} 

Link 到 copepen http://codepen.io/Saharalara/pen/Grxmmj

TL;DR: 这是 fiddle 以查看它的工作情况:https://jsfiddle.net/pnruje2g/6/


经过一番修改后,我发现了 4 个问题。

第一个是 non-HTTPS 环境中的 getCurrentPosition() 弃用,例如 Google Chrome.

中的 CodePen

这是我在 Google Chrome 中收到的确切消息:

getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.

如果您使用 Google Chrome,您可能想在不同的浏览器中尝试此操作。不过它确实适用于本地站点。

下一个问题是调用不存在的函数getDistanceFromLatLonInMiles()。我将其替换为对 getDistanceFromLatLonInKm().

的调用

第三个问题是试图分配一个不存在的 属性,您引用 inner.HTML 而不是 innerHTML

第四个问题是您的警报位置。目前他们只是坐在你的 JS 文件的底部,没有做任何事情。我们希望在完成计算后显示警报。我将您的提醒移到了 showLocation() 函数的末尾。