问题
Can anyone help me with the logic on how should I get the maximum/minimum coordinates, with an array of coodinates? What I'm trying to get is the longest distance it can get out of those array of coordinates. Ex.
var coordinates = [{ lat: -231, lng: 223l }, { lat: 43, lng: -4323 }, { lat: 42312, lng: -231 }, { lat: 435345, lng: -6563 }] // some filter calculation here... // This is what I need var min_coords = { lat, lng } var max_coords = { lat, lng }
回答1:
You can create arrays of the values, and then use Math.max
and Math.min
to get the highest and lowest values
var coordinates = [{
lat: -231,
lng: 223
}, {
lat: 43,
lng: -4323
}, {
lat: 42312,
lng: -231
}, {
lat: 435345,
lng: -6563
}]
var lat = coordinates.map(function(p) {return p.lat});
var lng = coordinates.map(function(p) {return p.lng});
var min_coords = {
lat : Math.min.apply(null, lat),
lng : Math.min.apply(null, lng)
}
var max_coords = {
lat : Math.max.apply(null, lat),
lng : Math.max.apply(null, lng)
}
console.log(min_coords);
console.log(max_coords);
回答2:
A solution using Array.prototype.reduce
to filter through the array for the min and max values - demo below:
var coordinates=[{lat:-231,lng:223},{lat:43,lng:-4323},{lat:42312,lng:-231},{lat:435345,lng:-6563}];
var result = coordinates.reduce(function(prev,curr){
if(curr.lat < prev.min_cords.lat)
prev.min_cords.lat = curr.lat;
if(curr.lat > prev.max_cords.lat)
prev.max_cords.lat = curr.lat;
if(curr.lng < prev.min_cords.lng)
prev.min_cords.lng = curr.lng;
if(curr.lng > prev.max_cords.lng)
prev.max_cords.lng = curr.lng;
return prev;
},{min_cords:{lat:Infinity,lng:Infinity},max_cords:{lat:-Infinity,lng:-Infinity}});
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
来源:https://stackoverflow.com/questions/40506024/how-to-get-maximum-minimum-boundaries-with-array-of-coordinates