平均Lng / Lat NaN问题

时间:2014-02-17 05:49:09

标签: google-maps latitude-longitude average

我是一名业余程序员,正在使用google maps API处理我想到的项目。长话短说,我试图创建一个具有n个点的平均经度和纬度的变量。我已经知道我有一个lng / lat坐标数组,但我很难将它们转换为一种格式,我可以将其用作谷歌地图LatLng方法的输入。

我已经引用了这个问题,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);
    }
  });
}}

1 个答案:

答案 0 :(得分:1)

2个问题:

  • results[0].geometry.location不是数组,而是一个对象(google.maps.LatLng)。使用lat()lng()方法检索纬度和经度
  • var avgLat = 0;
       var avgLng = 0;
        var j = 0;

    您必须将其移至循环外部,否则将在每个循环中清除变量。