1
我是一个业余程序员和一个项目,我在使用谷歌地图API的头脑工作。长话短说,我试图创建一个具有n个点的平均经度和纬度的变量。我的意思是我有一个lng/lat坐标数组,但我努力将它们转换成可用作Google Maps LatLng方法的输入的格式。平均LNG /纬度NaN的问题
现在我已经提到这太问题,Find the average (center) of lats/lngs,和许多其他网站一个月了,但我一直无法理解或实现一个解决方案。我觉得我错过了简单的东西,但一个月来我一直在抨击我的头,并没有到任何地方。任何意见或帮助与此将不胜感激。
//GOOGLE MAPS API SCRIPTS
var streetarray = document.getElementsByName("street");
var cityarray = document.getElementsByName("city");
var geocoder;
var map;
var results;
var mapArray = new Array();
var avgLat;
var avgLng;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
//centered on Carrollton, Texas -- Change lat,long values to change initial map area
center:
new google.maps.LatLng(32.999173, -96.897413)
}
//change Id reference to the div/container that contains the google map
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
//Loop through and concate street and city values to find long,lat values for all fields
for (var cName = 0; cName < namearray.length; cName++){
var address = streetarray[cName].value + cityarray[cName].value;
//start geocode copy & paste text from API reference
geocoder.geocode({ 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var results = results[0].geometry.location;
map.setCenter(results);
var marker = new google.maps.Marker({
map: map,
position: results,
});
//Push lng/lat locations to the mapArray
mapArray.push(results);
//Loop through mapArray to add Lat/Lng values, and then divide by j (number of locations) to find the average
for (var i in mapArray) {
var avgLat = 0;
var avgLng = 0;
var j = 0;
var avgLat = (avgLat + mapArray[i][1]);
var avgLng = (avgLng + mapArray[i][2]);
console.log(mapArray, avgLat, avgLng);
j++;
}
avgLat = avgLat/j;
avgLng = avgLng/j;
var markerCircle = new google.maps.Circle({
center: results,
radius: 15000,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
})
markerCircle.setMap(map);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}}
这是有道理的!我没有完全理解循环的问题.....谢谢! 关于结果的一个问题...评论。我创建了一个名为mapArray的新数组,并将结果[0] .geometry.location的值推送到该数组,以便我可以遍历它们并以这种方式拉动lat()lng();是做到这一点的最佳方式,还是直接使用结果对象会更好? –
你不能直接工作,没有任何帮手,因为答案一个接一个地到达。你可以做的,而不是额外的循环是存储3个全局变量的标记数量,纬度和经度总和。每次获得响应时更新这些变量,并根据这些变量计算平均值,然后您不需要每次循环增加数组。 –
谢谢你们两位。 –