本文介绍了地理位置,使用for和javascript循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在为移动网站开发地理定位工具,到目前为止,我已经了解到了这一点:I'm working on a Geolocation tool for a mobile website and so far i got this: 地理位置验证 href = http://dev.opera.com/articles/view/how-to-use-the-w3c-geolocation-api/ rel = nofollow noreferrer>此处:The Geolocation verification from here:if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(successFunction, errorFunction);} else { console.log('Geolocation not enabled in your browser.');} Caspar的 toRad()函数此处:The toRad() function from Caspar's answer here:if (typeof(Number.prototype.toRad) === "undefined") { Number.prototype.toRad = function() { return this * Math.PI / 180; }}和 successFunction()从第一个链接可移动类型脚本和其他一些修改:and the successFunction() from the first link, Movable Type Scripts and some others modifications:function successFunction(position) { var lat1 = position.coords.latitude; var lon1 = position.coords.longitude; function calcdist(nLoja,nLat,nLong) { this.loja = nLoja; this.lat = nLat; this.long = nLong; } aLocal = new Array(3) aLocal[0] = new calcdist("leblon",-22.982279,-43.217792); aLocal[1] = new calcdist("ipanema",-22.98376,-43.212138); aLocal[2] = new calcdist("barra",-22.999118,-43.357867); var i = 0; //for (var i = 0; i < 4; i++){ lat2 = aLocal[i].lat; lon2 = aLocal[i].long; var R = 6371; var dLat = (lat2-lat1).toRad(); var dLon = (lon2-lon1).toRad(); var lat1 = lat1.toRad(); var lat2 = lat2.toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; var thediv = document.getElementById('locationinfo'); thediv.innerHTML = '<p>Distance user-' + aLocal[i].loja + ': ' + d + '</p>'; //}}我的桌面和我的iPhone。问题出在我注释 i = 0; 行并取消注释 for()语句之后(以及作为结束括号)。 Chrome的控制台向我返回错误:This works just fine on my desktop and my iphone. The problem comes when i comment the i=0; line and uncomment the for() statement right after (as well as the closing bracket). Chrome's console returns me an error:Uncaught TypeError: Cannot read property 'lat' of undefined为此行:lat2 = aLocal[i].lat;循环的原因是我想做x次数学运算以检查哪家商店更近到用户(通过获得用户与每个商店之间的最小距离)。但是我似乎无法找出为什么不允许循环的原因。The reason for the loop is that i want to do the math x times to check which shop is closer to the user (by getting the smallest distance between user and each shop). But i can't seem to find out why it won't allow the loop.提前很多感谢。推荐答案 aLocal 具有三个元素。您的循环从0到3,所以有4个元素。aLocal has three elements. Your loop goes from 0 to 3 so that are 4 elements.for (var $i = 0; $i < aLocal.length; $i++) { //...} 这篇关于地理位置,使用for和javascript循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-05 16:22