循环对象数组,直到lat/lng不为零

Loop through object array until lat/lng is not zero

本文关键字:lng lat 对象 数组 直到 循环      更新时间:2023-09-26

我有一个带有标记lat/lngs的对象数组,有时地址没有经过地理编码,所以我想跳过lat:0,lng:0。我现在要做的是设置一个循环,使它在数组中循环并找到第一个不为null的对象。

它不会显示地图,说它是未定义的。

这就是我到目前为止所想到的。

var Points = [{
    lat: 0,
    lng: 0
}, {
    lat: 42,
    lng: -72
}, {
    lat: 41,
    lng: -73
}];
function initMap()
{
    for (var i = 0; i < Points.length; i++)
    {
        if (Points[i].lat * Points[i].lng != 0)
        {
            map = new google.maps.Map(document.getElementById('map'),
            {
                center: new google.maps.LatLng(Points[i].lat, Points[i].lng),
                zoom: 10,
                scaleControl: true
            })
            break;
        }
        else
        {
            continue;
        }
    }
}

使用array.filter:

var Points = [{
    lat: 0,
    lng: 0
}, {
    lat: 42,
    lng: -72
}, {
    lat: 41,
    lng: -73
}];
/**
 Given an object with `lat` and `lng` properties, return true if both `lat` and `lng` !== 0
 
 - parameter p: the Point to test
 
 - return: Bool true if both `lat` and `lng` !== 0
 */
function pointIsNonZero(p) {
  return p.lat !== 0 && p.lng !== 0;
}
console.log(Points.filter(pointIsNonZero));