我一直在通过 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!");
}
链接到 copepen http://codepen.io/Saharalara/pen/Grxmmj
最佳答案
TL;DR:这是可以看到它工作的 fiddle :https://jsfiddle.net/pnruje2g/6/
修改了一下之后,我发现了 4 个问题。
第一个是在非 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()
函数的末尾。
关于javascript - 警报问题 - 使用 haversine 距离公式进行地理定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42034049/