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個全局變量的標記數量,緯度和經度總和。每次獲得響應時更新這些變量,並根據這些變量計算平均值,然後您不需要每次循環增加數組。 –
謝謝你們兩位。 –